package com.sam.im.heiqun.uis.activities;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.google.gson.Gson;

import com.iceteck.silicompressorr.SiliCompressor;
import com.melink.bqmmsdk.bean.Emoji;
import com.melink.bqmmsdk.sdk.BQMM;
import com.melink.bqmmsdk.sdk.BQMMMessageHelper;
import com.melink.bqmmsdk.sdk.IBqmmSendMessageListener;
import com.melink.bqmmsdk.widget.BQMMMessageText;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AAentivity;
import com.sam.im.heiqun.entities.AddFriendEntity;
import com.sam.im.heiqun.entities.AddFriendResultEntivity;
import com.sam.im.heiqun.entities.FanYiBean;
import com.sam.im.heiqun.entities.FileMsgEntivity;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImMessageData;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.ImageSendEntity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.PathEntivity;
import com.sam.im.heiqun.entities.PayString;
import com.sam.im.heiqun.entities.ReadedEntity;
import com.sam.im.heiqun.entities.RedPacketEntivity;
import com.sam.im.heiqun.entities.RedPacketHistoryEntivity;
import com.sam.im.heiqun.entities.TransferViewEntivity;
import com.sam.im.heiqun.entities.TransfreCreateEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.entities.beans.CollectInfo;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.entities.model.FileProEtivity;
import com.sam.im.heiqun.entities.model.LocationEntivity;
import com.sam.im.heiqun.entities.model.WithdrawEntity;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.beans.BGchat;
import com.sam.im.heiqun.uis.beans.BGsetAll;
import com.sam.im.heiqun.uis.beans.FriendmpBean;
import com.sam.im.heiqun.uis.dialogs.MyAlertDialogManages;
import com.sam.im.heiqun.uis.widgets.AudioRecordButton;
import com.sam.im.heiqun.uis.widgets.ChatBottomViews;
import com.sam.im.heiqun.uis.widgets.MediaManager;
import com.sam.im.heiqun.uis.widgets.SpaceItemDecoration;
import com.sam.im.heiqun.uis.widgets.pulltorefresh.WrapContentLinearLayoutManager;
import com.sam.im.heiqun.uis.widgets.pulltorefresh.base.PullToRefreshView;
import com.sam.im.heiqun.utils.AudioModeManager;
import com.sam.im.heiqun.utils.ContentUtils;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.IMMessageUtil;
import com.sam.im.heiqun.utils.ImageCheckoutUtil;
import com.sam.im.heiqun.utils.JsonUtil;
import com.sam.im.heiqun.utils.KeyBoardUtils;
import com.sam.im.heiqun.utils.PictureUtil;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.view.PullToRefreshListener;
import com.sam.im.heiqun.view.PullToRefreshRecyclerView;
import com.sam.im.heiqun.view.RecordButton;


import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.utils.ActivityUtil;
import com.yuyh.library.utils.Utils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.log.LogUtils;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;

import com.sam.im.heiqun.utils.StringUtils;
import com.zq.utils.StringUtil;

/**
 * 私聊
 * //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
 */
public class ChatActivity extends ChatBaseActivity implements TextWatcher, View.OnLayoutChangeListener, PullToRefreshListener, AudioRecordButton.AudioFinishRecorderListener {

    private static final int SEND_CLEAN = 0X100;
    private static final int UP_ERROR = 0X1011;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    /* @BindView(R.id.red_packet)
     LinearLayout redPacket;
     @BindView(R.id.transfer_accounts)
     LinearLayout transfer_accounts;*/
    @BindView(R.id.red_0)
    ImageView red0;
    @BindView(R.id.red_1)
    ImageView red1;
    @BindView(R.id.red_2)
    ImageView red2;
    @BindView(R.id.red_3)
    ImageView red3;
    @BindView(R.id.red_4)
    ImageView red4;
    @BindView(R.id.red_5)
    ImageView red5;
    @BindView(R.id.red_6)
    ImageView red6;
    @BindView(R.id.red_7)
    ImageView red7;
    @BindView(R.id.red_8)
    ImageView red8;
    @BindView(R.id.red_9)
    ImageView red9;
    @BindView(R.id.red_10)
    ImageView red10;
    @BindView(R.id.red_11)
    ImageView red11;
    @BindView(R.id.red_12)
    ImageView red12;
    @BindView(R.id.red_13)
    ImageView red13;
    @BindView(R.id.view_back)
    View viewBack;
    @BindView(R.id.imgdelete)
    ImageView imgDelete;
    @BindView(R.id.loading)
    ProgressBar loading;
    @BindView(R.id.linear_bottom_kl)
    LinearLayout linear_bottom_kl;
    @BindView(R.id.txt_kl_content)
    TextView txt_kl_content;

    private AnimatorSet set;
    private int height;
    private String redPackageId;
    private RelativeLayout relative;
    private PullToRefreshRecyclerView myList;
    public static boolean isLive = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x100:
                    shuxingSet(red7, 4600, 120, 700);
                    shuxingSet(red8, 3100, 110, 300);
                    shuxingSet(red9, 4200, 80, 500);
                    shuxingSet(red10, 2800, 50, 380);
                    shuxingSet(red11, 4700, -70, 400);
                    shuxingSet(red12, 3400, -120, 700);
                    shuxingSet(red13, 6100, -70, 3300);
                    handler.sendEmptyMessageDelayed(0x110, 3300);
                    break;
                case 0x110:
                    doRainRed();
                    break;
                case 99:

                    break;
            }
        }
    };

    private ChatRecyclerAdapter tbAdapter;
    private SendMessageHandler sendMessageHandler;
    private static WrapContentLinearLayoutManager wcLinearLayoutManger;

    private static Socket mSocket;
    private String uuid = "";
    private Gson gson;
    private static final int RESULT_RED_PACKET_SEND = 101;
    public static final int RESULT_TRANSFER_SEND = 102;
    private static final int RESULT_TRANSFER_GET = 103;
    public static final int RESULT_LOCATION = 104;
    public static final int REQUST_SENDTOFRIEND = 111;//发送消息给好友
    public static final int RESULT_SEND_FILE = 112;//发送文件
    public static final int COMMIT_FINISH = 202;//文件上传完毕
    public static final int FILE_DOWNLOAD_OK = 222;//文件下载完成
    public static final int VEDIO_FINISH = 212;//视屏上传完毕
    private String TAG = "-----";
    PGService mPgService;
    private Dialog redDialog;
    private UserEntivity userEntivity;
    private int lastVisibleItem = 0;
    private static int visibPosition;
    private static LinearLayoutManager layoutManager;
    private static View v;
    private int lastVisibleItemPosition;
    private static View childAt;
    private static int tbsizes;
    private int screenHeight;
    private static int firstTag = -1;
    private boolean isspeakerphone;//默认是免提
    private PopupMenu popupMenu; // 消息弹框菜单
    private Menu menu;
    private long sendMsgId;
    private String sendmsgId;
    private ImMessage choseimMessage;
    private ImMessage getimsg;
    private BQMM bqmm; //表情云
    private ImMessage fileimMessage;
  //  private ImMessage vedioMessage;
    private FileMsgEntivity fileMsgEntivity;
    private AudioModeManager audioModeManger;
    // private List<String> readMsgs  = new ArrayList<>();//已读的消息列表
    // private static int scaleY;
    private boolean mIsRefreshing = false;
    private int playingItemvoice = -1;
    private boolean thisistag;
    private long firsttimes;
    private long seceoundtimes;
    private long uid;
    private ImMessage mredPacketImMessage;
    private List<ImMessage> mRedMessages = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_chat;
    }

    @Override
    protected String getTitleText() {

        right.setVisibility(View.VISIBLE);
        right.setImageResource(R.drawable.lanmu_person);
        destid = getIntent().getLongExtra("destid", 0l);
        uid = getIntent().getLongExtra("destid", 0l);
        getimsg = (ImMessage) getIntent().getSerializableExtra("msg");
        ImFriendEntivity idFriendsInfo = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
        friendheadurl = (null == idFriendsInfo ? "" : idFriendsInfo.getHeadUrl());
        userEntivity = ToolsUtils.getUser();

        Log.i(TAG, "getTitleText: --------头像------进入---------userEntivity.getHeadUrl()=" + userEntivity.getHeadUrl());
        String name = "";
        if (null != idFriendsInfo) {
            /**  场景：当好友修改了名称或头像，我重新登录后好友列表更新了信息，但是消息列表未更新，这里需要判断后给消息列表发消息  */
            List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=?", new String[]{ToolsUtils.getMyUserId() + "", destid + ""}, null, "time desc", null);

            MessageEntivity mMessageEntivity;
            if (messageEntivities.size() > 0) {
                mMessageEntivity = messageEntivities.get(0);
                mMessageEntivity.setImgUrl(idFriendsInfo.getHeadUrl());
                mMessageEntivity.setNick(idFriendsInfo.getName());
                mMessageEntivity.save();
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
            }
            name = ToolsUtils.getNick(idFriendsInfo);
        }
        return name;
    }

    private MsgEntity msgEntity;

    public void sendType(String data, String id) {
        msgEntity = new MsgEntity();
        msgEntity.setMsgString(data);
        String msg = new Gson().toJson(msgEntity);
        sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, Integer.parseInt(id));
    }


    private final int REQUEST_EXTERNAL_STORAGE = 1;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void init() {
        isLive = true;
        tvTitle.setText(getTitleText());
        mPgService = PGService.getInstance();
//        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
        getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//点了屏幕
        // 设置输入框的 内容变化监听
        mEditTextContent.addTextChangedListener(this);
        gson = new Gson();
        uuid = Utils.getUDID(ChatActivity.this);
        fromid = ToolsUtils.getMyUserId();

        if (sendMessageHandler != null) {
            sendMessageHandler.sendEmptyMessage(PULL_TO_REFRESH_DOWN);
        }
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int id = (int) destid;
        notificationManager.cancel(id);//注销单人聊天
        mSocket = App.socket;
        //  Collections.reverse(tblist);
        height = getWindowManager().getDefaultDisplay().getHeight();
        tbAdapter = new ChatRecyclerAdapter(this, tblist, new ChatRecyclerAdapter.OnreadMsgListenler() {
            @Override
            public void sendread(List<String> msgids) {
                sendReads(msgids);
            }
        }, new ChatRecyclerAdapter.OnlongclickMsgListenler() {


            @Override
            public void onOnTextMsgClicked(String text) {
                if (text.isEmpty()) {
                    return;
                }

                //调起系统浏览器打开链接
                String link = text;
                if (link.startsWith("www.")
                        || link.startsWith("alipays://") //支付宝
                        || link.startsWith("mailto://") //邮件
                        || link.startsWith("tel://")//电话
                        || link.startsWith("dianping://")//大众点评
                        || link.startsWith("weixin://") //微信
                        ) {
                    link = "http://" + link;

                    Intent intent = new Intent(ChatActivity.this, WebViewActivity.class);
                    intent.putExtra("url", link);
                    startActivity(intent);
                   /* Uri uri = Uri.parse(link);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);*/
                } else if (link.startsWith("http://") || link.startsWith("https://")) {
                    //是合法的链接
                    Intent intent = new Intent(ChatActivity.this, WebViewActivity.class);
                    intent.putExtra("url", link);
                    startActivity(intent);

                  /*  Uri uri = Uri.parse(link);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);*/
                }
            }

            //这里应该是处理消息的
            @Override
            public void msgLongClick(int position, int type, View view) {
                choseimMessage = tblist.get(position);
                sendmsgId = choseimMessage.getMsgId();
                //根据消息id撤回
                sendMsgId = choseimMessage.getId();
                Long sendTime = choseimMessage.getSendTime();
                long nowtime = System.currentTimeMillis();
                long l = (nowtime - sendTime) / (1000 * 60);//时间差两分钟内
                boolean canwithdraw = l <= 2;
                switch (type) {
//                    case ChatRecyclerAdapter.FROM_USER_LOCATION:
                    //接收文本消息
                    case ChatRecyclerAdapter.FROM_USER_MSG:
                    case ChatRecyclerAdapter.FROM_USER_VOICE:
                    case ChatRecyclerAdapter.FROM_USER_EMOJI:
                    case ChatRecyclerAdapter.FROM_USER_FILE:
                    case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                        initMenu(view, false, type, true);
                        break;
                    case ChatRecyclerAdapter.FROM_USER_IMG:

                        ImageSendEntity sendEntity = JsonUtil.toObject(choseimMessage.getContent(), ImageSendEntity.class);
                        boolean canForward = sendEntity == null || sendEntity.isCanForward();
                        initMenu(view, false, type, canForward);
                        break;
                    case ChatRecyclerAdapter.FROM_USER_VEDIO:
                        VedioEntity vedioEntity = JSON.parseObject(choseimMessage.getContent(), VedioEntity.class);
                        initMenu(view, false, type, vedioEntity.isCanForward());
                        break;
                   /*  FileMsgEntivity fileMsgEntivity = new Gson().fromJson(choseimMessage.getContent(),FileMsgEntivity.class);
                        initMenu(view, fileMsgEntivity.isFilished(),type);
                        break;*/
                    case ChatRecyclerAdapter.TO_USER_IMG:
//                    case ChatRecyclerAdapter.TO_USER_LOCATION:
                        //发送文本消息
                    case ChatRecyclerAdapter.TO_USER_MSG:

                    case ChatRecyclerAdapter.TO_USER_VOICE:
                    case ChatRecyclerAdapter.TO_USER_EMOJI:
                    case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                    case ChatRecyclerAdapter.TO_USER_VEDIO:
                    case ChatRecyclerAdapter.TO_USER_FILE:
                        initMenu(view, canwithdraw, type, true);
                        break;
                    case ChatRecyclerAdapter.FROM_USER_READDELETE:
                    case ChatRecyclerAdapter.TO_USER_READDELETE:
                        String imageUrlSrc = "";
                        // Log.i("info","适配器接收到的内容=="+tbub.toString());
                        if (tblist.get(position).getFilePath() != null && !tblist.get(position).getFilePath().equals("")) {
                            imageUrlSrc = tblist.get(position).getFilePath();
                        } else if (tblist.get(position).getFileUrl() != null) {
                            imageUrlSrc = tblist.get(position).getFileUrl();
                        }
                        imgDelete.setVisibility(View.VISIBLE);

                        Glide.with(ChatActivity.this).load(imageUrlSrc).into(new GlideDrawableImageViewTarget(imgDelete) {
                            @Override
                            public void onLoadStarted(Drawable placeholder) {
                                super.onLoadStarted(placeholder);
                               /* if(smallImageView!=null){
                                    smallImageView.setVisibility(View.VISIBLE);
                                    Glide.with(context).load(imgurl).into(smallImageView);
                                }*/
                                loading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                                loading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                                super.onResourceReady(resource, animation);
                                loading.setVisibility(View.GONE);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                            }
                        });
                        break;
                }
            }
        });
        myList.setAlpha(0f);

        wcLinearLayoutManger = new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //wcLinearLayoutManger.setReverseLayout(true);//倒序输入
        //wcLinearLayoutManger.setStackFromEnd(true);
        myList.setLayoutManager(wcLinearLayoutManger);
//        myList.setItemAnimator(new SlideInOutBottomItemAnimator(myList));
        myList.setAdapter(tbAdapter);

        myList.setOnTouchListener(
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (mIsRefreshing) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );
        sendMessageHandler = new SendMessageHandler(this);
        tbAdapter.isPicRefresh = true;
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing_twelve);
        myList.addItemDecoration(new SpaceItemDecoration(spacingInPixels));
        /*myList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();
                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount - 1)) {
                        myList.setAd);
                        //加载更多功能的代码
                    }
                }
                Log.i("info","滑动中111");
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });*/
       /* myList.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                Log.i("info","滑动中222");
            }
        });*/
        sendMessageHandler = new SendMessageHandler(this);
        tbAdapter.isPicRefresh = true;
        tbAdapter.notifyDataSetChanged();//防止界面错位
        tbAdapter.setSendErrorListener(new ChatRecyclerAdapter.SendErrorListener() {

            @Override
            public void onClick(int position) {
                setSocket();
                final ImMessage tbub = tblist.get(position);
                ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                if (null != imMessage) {
                    imMessage.setSendState(Constant.SENDING);
                    imMessage.save();
                    if (null != tblist && tblist.size() > 0) {
                        for (int j = 0; j < tblist.size(); j++) {
                            if (("" + imMessage.getId()).equals("" + tblist.get(j).getId())) {
                                tblist.set(j, imMessage);
                            }
                        }
                    }
                    sendMessageHandler.sendEmptyMessage(SEND_OK);
                    socketSend(imMessage, null, 0, 0);
                } else {
                    tbub.setSendState(Constant.SENDING);
                    tbub.save();
                    if (null != tblist && tblist.size() > 0) {
                        for (int j = 0; j < tblist.size(); j++) {
                            if (("" + tbub.getId()).equals("" + tblist.get(j).getId())) {
                                tblist.set(j, tbub);
                            }
                        }
                    }
                    sendMessageHandler.sendEmptyMessage(SEND_OK);
                    socketSend(tbub, null, 0, 0);
                }
            }
        });
        tbAdapter.setOnStartplayVoice(new ChatRecyclerAdapter.onStartplayVoice() {
            @Override
            public void onclickvoice(int position) {
                playingItemvoice = position;
                //  setstopvoice(position);

            }
        });


        tbAdapter.setImessageOnlongClickListener(new ChatRecyclerAdapter.ImessageOnlongClick() {
            @Override
            public void longClickMessage(int position, int type) {
                Toast.makeText(ChatActivity.this, "点击了消息" + position, Toast.LENGTH_SHORT).show();
            }
        });

        tbAdapter.setVoiceIsReadListener(new ChatRecyclerAdapter.VoiceIsRead() {

            @Override
            public void voiceOnClick(int position) {
                for (int i = 0; i < tbAdapter.unReadPosition.size(); i++) {
                    if (tbAdapter.unReadPosition.get(i).equals(position + "")) {
                        tbAdapter.unReadPosition.remove(i);
                        break;
                    }
                }
            }
        });

        tbAdapter.setRedPacketListener(new ChatRecyclerAdapter.RedPacketOnClick() {

            @Override
            public void redOnClick(ImMessage imMessage, int type) {
                String content = imMessage.getContent();
                Bundle bundle = new Bundle();
//                RedPacketEntivity redPacketEntivity= ToolsUtils.getRedPacket(content);

                redPackageId = ToolsUtils.getRedPacketInfo(content);
                switch (type) {//0-获取；1-发送
                    case 0://
                        if (!ToolsUtils.currentNetState(ChatActivity.this)) {//当前网络不可用
                            break;
                        }

                        getRedPacketHistory(redPackageId, imMessage);

                        break;
                    case 1:
                        showProgress(getResources().getString(R.string.now_open));
                        mPgService.getRedPacketHistory(redPackageId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
                            @Override
                            protected void onResultError(ApiException ex) {
                                hideProgress();
                                showToast(getResources().getString(R.string.net_error));
                            }

                            @Override
                            public void onNext(RedPacketHistoryEntivity redPacketHistoryEntivity) {
                                hideProgress();
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("redPacketId", redPacketHistoryEntivity);
                                bundle.putInt("type", 0);
                                startActivity(RedPackageDetailsActivity.class, bundle);
                            }
                        });
                        break;
                    case 2://获取转账
                        bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                        bundle.putInt("type", 1);
                        startActivityForResult(AffirmReceiveTransferActivity.class, RESULT_TRANSFER_GET, bundle);
                        break;
                    case 3://发送转账
                        bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                        bundle.putInt("type", 0);
                        startActivity(AffirmReceiveTransferActivity.class, bundle);
                        break;
                    case 4://付款

                        break;
                    case 5://收款

                        break;
                }
            }
        });

        tbAdapter.setFanYiListener(new ChatRecyclerAdapter.FanYiOnClick() {
            @Override
            public void fanYiOnClick(String content, int type, int isRefresh) {//isRefresh=0-不是；1-是并显示；2-是并隐藏
                if (0 == isRefresh) {
                    getFanYi(content, type);
                } else {
                    ImMessage imm = tblist.get(type);
                    if (1 == isRefresh) {
                        imm.setIsShowFY("1");
                    } else {
                        imm.setIsShowFY("0");
                    }
                    tblist.set(type, imm);
                    sendMessageHandler.sendEmptyMessage(REFRESH_FANYI);
                }
            }
        });
        tbAdapter.setFriendnickname(getTitleText());//把好友名字传递到适配器中
        tbAdapter.setHeadUserListener(new ChatRecyclerAdapter.HeadUserOnClick() {
            @Override
            public void detailsOnClick(int uid, int type) {
                if (0 == type) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("id", tblist.get(uid).getDestid());
                    bundle.putInt("type", 3);
                    startActivityForResult(FriendDetailActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
                }
            }
        });
        //消息长按监听
        //消息已读
       /* tbAdapter.setOnreadmsgListenler(new ChatRecyclerAdapter.OnreadMsgListenler() {
            @Override
            public void sendread(List<String> msgids) {

            }
        });*/
        //阅后即焚删除
        tbAdapter.setOnTouchUplistener(new ChatRecyclerAdapter.OnTouchUplistener() {
            @Override
            public void onTouchup(int position) {
                ImMessage touchmessage = tblist.get(position);
                imgDelete.setVisibility(View.GONE);
                tblist.remove(position);
                tbAdapter.notifyDataSetChanged();
                List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id=?", new String[]{touchmessage.getMsgId()});
                if (imMessages.size() > 0) {
                    imMessages.get(0).delete();
                }
            }
        });
        //邀请入群
        tbAdapter.setOnInviteJoinGroupClickListener(new ChatRecyclerAdapter.OnInviteJoinGroupClickListener() {
            @Override
            public void onInviteJoinGroupClick(String groupId) {

                PGService.getInstance().getNetApi().getGroupById(groupId, ToolsUtils.getMyUserId())
                        .compose(RxJavaUtil.<ImGroupEntivity>applySchedules())
                        .compose(ChatActivity.this.<ImGroupEntivity>bindLifeCycle())
                        .compose(ChatActivity.this.<ImGroupEntivity>applyProgress(""))
                        .subscribe(new AbsAPICallback<ImGroupEntivity>() {
                            @Override
                            public void onNext(ImGroupEntivity groupEntivity) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("groupSeri", groupEntivity);
                                bundle.putLong("groupid", groupEntivity.getId());
                                startActivity(GroupDetailsActivity.class, bundle);
                            }

                            @Override
                            protected void onResultError(ApiException ex) {

                            }
                        });
            }
        });
        tbAdapter.setSendFriendVerifyListener(new ChatRecyclerAdapter.SendFriendVerifyListener() {
            @Override
            public void sendFriendVerify() {

                View view = LayoutInflater.from(ChatActivity.this).inflate(R.layout.dialog_send_friend_request, null);
                final EditText editText = view.findViewById(R.id.et_send_content);
                editText.setHint(StringUtil.format(ChatActivity.this,R.string.hello_i_am,ToolsUtils.getUser().getName()));
                AlertDialog alertDialog = new AlertDialog.Builder(ChatActivity.this)
                        .setTitle(R.string.verify_apply)
                        .setMessage(R.string.verify_apply_content)
                        .setView(view)
                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                String string = editText.getText().toString();
                                if(TextUtils.isEmpty(string)){
                                    string = editText.getHint().toString();
                                }
                                requestFriend(string);
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create();
                alertDialog.show();
            }
        });
        //文件操作
        tbAdapter.setOnclickDownloadListenler(new ChatRecyclerAdapter.OnclickDownloadListenler() {
            @Override
            public void clickDown(final int positon, final int type) {// 0  接收  1  发送
                switch (type) {
                    case ChatRecyclerAdapter.FROM_USER_FILE://接收
                        AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                        builder.setTitle(getResources().getString(R.string.tip_down));
                        builder.setMessage(getResources().getString(R.string.start_down_file));
                        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final ImMessage imMessage = ImMessage.findById(ImMessage.class, tblist.get(positon).getId());
                                if (imMessage != null) {
                                    String content = imMessage.getContent();
                                    final FileMsgEntivity fileMsgEntivity = new Gson().fromJson(content, FileMsgEntivity.class);
                                    final String fileUrl = fileMsgEntivity.getFileUrl();
                                    if (null != fileUrl) {
                                        if (!ToolsUtils.isExsite(fileUrl)) {
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String s1 = HttpAssist.fileDown(fileUrl, 0, imMessage.getMsgId());
                                                    fileMsgEntivity.setFilished(true);
                                                    fileMsgEntivity.setFileUrl(fileUrl);
                                                    String s = new Gson().toJson(fileMsgEntivity);
                                                    tblist.get(positon).setFilePath(s1);
                                                    tblist.get(positon).setContent(s);
                                                    imMessage.setFilePath(s1);
                                                    imMessage.setContent(s);
                                                    imMessage.save();
                                                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                                }
                                            }).start();
                                        } else {
                                            fileMsgEntivity.setFilished(true);
                                            String s = new Gson().toJson(fileMsgEntivity, FileMsgEntivity.class);
                                            tblist.get(positon).setContent(s);
                                            imMessage.setContent(s);
                                            imMessage.save();
                                            sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                        }
                                    }
                                }
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        break;
                    case ChatRecyclerAdapter.TO_USER_FILE://发送的文件
                        ImMessage imMessage1 = tblist.get(positon);
                        String filePath1 = imMessage1.getFilePath();
                        Intent intent = ToolsUtils.openFile(filePath1);
                        if (intent != null) {
                            startActivity(intent);
                        } else {
                            showToast(getString(R.string.fileisdelete));
                        }
                        break;
                    case ChatRecyclerAdapter.TO_USER_VEDIO://用户暂时直接从本地读取
                        ImMessage immessage = tblist.get(positon);
                        String filePath = immessage.getFilePath();
                        String filepath = "";
                        PathEntivity pathEntivity = new Gson().fromJson(filePath, PathEntivity.class);
                        VedioEntity vedioEntity = new Gson().fromJson(immessage.getContent(), VedioEntity.class);
                        if (pathEntivity != null && null != pathEntivity.getVideoPath() && pathEntivity.getVideoPath().contains("storage")) {
                            File file = new File(pathEntivity.getVideoPath());
                            if (file.exists()) {//如果文件存在则从本地读取，不存在从网络路径读取
                                filepath = pathEntivity.getVideoPath();
                            } else {
                                filepath = vedioEntity.getVedioUrl();
                            }
                        } else {
                            filepath = vedioEntity.getVedioUrl();
                        }

                        startActivity(Play2Activity.newIntent(ChatActivity.this, filepath, vedioEntity, null));

                      //  startActivity(PlayActivity.newIntent(ChatActivity.this, filepath, vedioEntity, null));
                        break;
                    case ChatRecyclerAdapter.FROM_USER_VEDIO:
                        ImMessage imMessage = tblist.get(positon);
                        String content = imMessage.getContent();
                        vedioEntity = new Gson().fromJson(content, VedioEntity.class);
                        String vedioUrl = vedioEntity.getVedioUrl();
                        startActivity(Play2Activity.newIntent(ChatActivity.this, vedioUrl, vedioEntity, CollectInfo.fromImMessage(imMessage)));
                       // startActivity(PlayActivity.newIntent(ChatActivity.this, vedioUrl, vedioEntity, CollectInfo.fromImMessage(imMessage)));
                        break;
                }
            }
        });

        voiceBtn.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
            @Override
            public void onFinishedRecord(String s) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(s);
                    mediaPlayer.prepare();
                    int duration = mediaPlayer.getDuration();
                    float times = duration / 1000;
                    sendVoice(times, s);
                    mediaPlayer.release();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void readCancel() {

            }

            @Override
            public void noCancel() {

            }

            @Override
            public void onActionDown() {

            }

            @Override
            public void onActionUp() {

            }

            @Override
            public void onActionMove() {

            }
        });

//         voiceBtn.setAudioFinishRecorderListener(this);
        layoutManager = (LinearLayoutManager) myList.getLayoutManager();
        if (layoutManager != null) {
            lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            childAt = myList.getChildAt(lastVisibleItemPosition);
        }
        myList.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {
                switch (scrollState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        tbAdapter.handler.removeCallbacksAndMessages(null);
                        tbAdapter.isPicRefresh = false;
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        tbAdapter.handler.removeCallbacksAndMessages(null);
                        KeyBoardUtils.hideKeyBoard(ChatActivity.this,
                                mEditTextContent);
                        tbAdapter.isPicRefresh = true;
                        reset();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
               /* if (wcLinearLayoutManger != null) {
                    lastVisibleItem = wcLinearLayoutManger.findLastVisibleItemPosition();
                }*/
            }
        });
        super.init();
        Log.i("info", "imgsize = " + imageList.size());
        if (null != getimsg) {
            // Log.i("info","转发给好友");
            senmsgtoFriend();//转发消息给好友
        }

    }

    private void setstopvoice(int position) {
        View voicePlay = (View) findViewById(position);
        int itemViewType = tbAdapter.getItemViewType(position);
        if (itemViewType == ChatRecyclerAdapter.TO_USER_VOICE) {
            voicePlay.setBackgroundResource(R.drawable.adj);
        } else if (itemViewType == ChatRecyclerAdapter.FROM_USER_VOICE) {
            voicePlay.setBackgroundResource(R.drawable.receiver_voice_node_playing003);
        }
        tbAdapter.stopPlayVoice(false);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        App.destid = destid;
        activityRootView.addOnLayoutChangeListener(this);
        initBQmm();
        setChatBG();
        updateReadShow(true);
        initRedKLMessage();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (bqmm != null) {
            bqmm.destroy();
        }
        MediaManager.isStart = false;
        MediaManager.pause();
    }

    @Override
    public void onStop() {
        EventBus.getDefault().post(Constant.STOP_VOICE_PLAY);
        clearMessage();
        App.destid = -1;
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        isLive = false;
        getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//点了屏幕
        tblist.clear();
        tbAdapter.notifyDataSetChanged();
        sendMessageHandler.removeCallbacksAndMessages(null);
        firstTag = -1;
        wcLinearLayoutManger = null;
        layoutManager = null;
        getimsg = null;
        v = null;
        if (MyAlertDialogManages.dlg != null) {
            MyAlertDialogManages.dlg.dismiss();
            MyAlertDialogManages.dlg = null;
        }
      /*  if (voiceBtn.mAudioManager != null) {
            if (voiceBtn.mAudioManager.mRecorder != null) {
                voiceBtn.mAudioManager.mRecorder = null;
                voiceBtn.mAudioManager = null;
            }
        }*/
        // voiceBtn.mp3handler.removeCallbacksAndMessages(null);
        if (myList.refreshHeader != null) {
            if (myList.refreshHeader.animator != null) {
                myList.refreshHeader.animator.cancel();
            }
        }
        myList.setheadNull();
        myList.removeAllHeaderViews();
        myList.removeAllFooterViews();
        if (audioModeManger != null)
            audioModeManger.unregister();
        super.onDestroy();
    }

    private void initRedKLMessage() {
//        mRedMessages
        mRedMessages.clear();
        List<ImMessage> imMessageList = ImMessage.find(ImMessage.class, "uniqueness=? and message_type=? and isklopen=?", new String[]{fromid + "_" + destid, "" + Constant.MESSAGE_TYPR_REDPACKTE, "false"},
                null, "send_time desc", " 0, 200");
        if (null != imMessageList && imMessageList.size() > 0) {
            for (int j = 0; j < imMessageList.size(); j++) {
                ImMessage imMessage = imMessageList.get(j);
                if (null == imMessage) continue;
                try {
                    RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                    if (null != redPacketEntivity && null != redPacketEntivity.getRedPacketType()
                            && "3".equals(redPacketEntivity.getRedPacketType())) {
                        mRedMessages.add(imMessage);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initRedKLOpenFns(final String uid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mredPacketImMessage = null;
                List<ImMessage> imMessageList = ImMessage.find(ImMessage.class, "uniqueness=? and message_type=? and isklopen=?", new String[]{fromid + "_" + destid, "" + Constant.MESSAGE_TYPR_REDPACKTE, "false"},
                        null, "send_time asc", " 0, 200");
                if (null != imMessageList && imMessageList.size() > 0) {
                    for (int j = 0; j < imMessageList.size(); j++) {
                        ImMessage imMessage = imMessageList.get(j);
                        if (null == imMessage) continue;
                        try {
                            RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                            if (null != redPacketEntivity
                                    && uid.equals("" + redPacketEntivity.getRedPacketId())) {
                                imMessage.setIsklopen(true);
                                imMessage.save();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (null != mRedMessages && mRedMessages.size() > 0) {
                    try {
                        int j = 0;
                        for (ImMessage imMessage : mRedMessages) {
                            if (null != imMessage) {
                                RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                                if (null != redPacketEntivity) {
                                    if (uid.equals("" + redPacketEntivity.getRedPacketId())) {
                                        mRedMessages.remove(j);
                                        return;
                                    }
                                }
                            }
                            j++;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    /**
     * 发送AA收款 transfer/aaTrans
     * counts 收款个数 number @mock=2
     * destId 群或者用户id string @mock=17228
     * destType 1个人 2群组 number @mock=1
     * msg 收款显示文字 string @mock=AA收款
     * totalAmount 总金额 number @mock=2
     * userId
     */
    //AA收款
    @Override
    protected void sendAAcollection(final String nums, final String money, final String discrible, final String amt) {
        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        String destid1=Long.toString(destid);//把destid强转成string类型
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("counts", nums);
        json.put("destType", "1");
        json.put("destId", destid1);
        json.put("totalAmount", money);
        json.put("userId", userId);
        json.put("msg", discrible);
        String content = RequestRSAUtils.setRsaContent(json);
        mPgService.aaTrans(content).subscribe(new AbsAPICallback<AAentivity>() {
        //mPgService.aaTrans(nums, "" + destid, "1", discrible, money, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<AAentivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.net_error));
            }

            @Override
            public void onNext(AAentivity aAentivity) {
                hideProgress();

                setSocket();

                String content = new Gson().toJson(aAentivity);
                long currentTime = System.currentTimeMillis();
                ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_AA, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                        Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, Constant.MESSAGE_TYPR_AAMONEY_GET,
                        currentTime, System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, userEntivity.getHeadUrl());
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(SEND_OK);
                socketSend(imMessage, null, 0, 0);
            }
        });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    /*发送已读消息*/
    private void sendReads(List<String> readMsgs) {
        if (readMsgs.size() > 0) {
//            String content = readMsgs.get(readMsgs.size()-1);
            String content = "";
            JSONArray jsarray = new JSONArray();
            for (String readMsg : readMsgs) {
                JSONObject ob = new JSONObject();
                try {
                    ob.put("id", readMsg);
                    jsarray.put(ob);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            content = jsarray.toString();
            setSocket();
            final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_MSG_READ, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, Constant.MESSAGE_TYPR_READ,
                    System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, " ");
            //sendMessageHandler.sendEmptyMessage(SEND_OK);
            socketSend(imMessage, null, 0, 0);
        }

    }

    /**
     * 转发消息给好友
     */
    private void senmsgtoFriend() {
        getimsg.setDestid(destid);
        int type = -1;
        String content = getimsg.getContent();
        String imgurl = "";
        Log.i(TAG, "senmsgtoFriend: ***************getimsg.getMessageType()**" + getimsg.getMessageType());
        switch (getimsg.getMessageType()) {
            case Constant.MESSAGE_TYPR_VOICE:
                type = ChatRecyclerAdapter.TO_USER_VOICE;
                break;
            case Constant.MESSAGE_TYPR_VEDIO:
                type = ChatRecyclerAdapter.TO_USER_VEDIO;
                break;
            case Constant.MESSAGE_TYPR_FILE:
                type = ChatRecyclerAdapter.TO_USER_FILE;
                break;
            case Constant.MESSAGE_TYPR_IMAGE://图片
                type = ChatRecyclerAdapter.TO_USER_IMG;
                imgurl = getimsg.getContent();
                // Log.i("info", "imgurl==" + imgurl + " imglistsize==" + imageList.size());
                //  imageList.add(imgurl);
                //  Log.i("info"," imglistsize=="+imageList.size());
                //  imagePosition.put(tblist.size(), imageList.size() - 1);
                break;
            case Constant.MESSAGE_TYPR_LOCATION://位置
                type = ChatRecyclerAdapter.TO_USER_LOCATION;
                //  LocationEntivity locationEntivity = new Gson().fromJson(getimsg.getContent(),LocationEntivity.class);
                //imgurl = locationEntivity.getUrl() ;
                break;
            case Constant.MESSAGE_TYPR_TEXT://文本
                type = ChatRecyclerAdapter.TO_USER_MSG;
                break;
            case Constant.MESSAGE_TYPR_BQEMOJI://表情
                // Log.i("info","MESSAGE_TYPR_BQEMOJIcontent=="+content);
                MsgEntity receirvemsg = new Gson().fromJson(content, MsgEntity.class);
                if (receirvemsg.getMsgCodes() != null && !"".equals(receirvemsg.getMsgCodes())) {
                    //大表情
                    type = ChatRecyclerAdapter.TO_USER_EMOJI;
                } else {
                    //图文混排
                    type = ChatRecyclerAdapter.TO_USER_EMOJI_TEXT;
                }
                break;
            case Constant.MESSAGE_TYPR_AAMONEY_GET:
                type = ChatRecyclerAdapter.TO_USER_AA;
                break;
        }
        setSocket();
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, type, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, getimsg.getMessageType(),
                System.currentTimeMillis(), System.currentTimeMillis(), 0, getimsg.getFilePath(), fromid + "_" + destid, getimsg.getUserVoiceTime(), userEntivity.getHeadUrl());
        //  Log.i("info","转发的消息=="+imMessage.toString());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

    }

    /**
     * 获取红包详情
     *
     * @param uId
     */
    public void getRedPacketHistory(final String uId, final ImMessage imMessage) {
        final RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
        mPgService.getRedPacketHistory(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(RedPacketHistoryEntivity data) {
                if ("1".equals(data.getRedPacket().getStatus())) {//未领取
                    if (null != redPacketEntivity && "3".equals(redPacketEntivity.getRedPacketType())) {

                        mredPacketImMessage = imMessage;

                        String command = "";
                        if (null == redPacketEntivity.getCommand() || "".equals(redPacketEntivity.getCommand())) {
                            command = getResources().getString(R.string.gx_facai);
                        } else {
                            command = redPacketEntivity.getCommand();
                        }
                        txt_kl_content.setText(command);
                        linear_bottom_kl.setVisibility(View.VISIBLE);

                    } else {
                        redDialog = MyAlertDialogManages.initShowRedPacket(ChatActivity.this, data.getRedPacket().getHeadUrl(),
                                ToolsUtils.getNick(ToolsUtils.getMyFriendForId(destid)), data.getRedPacket().getRedPacketContent(),
                                data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                                    @Override
                                    public void onOkImageClick(ImageView mImageView) {
                                        ToolsUtils.startAnimal(mImageView);
                                        openRedPacket(uId);
                                    }
                                });
                    }
                } else if ("2".equals(data.getRedPacket().getStatus())) {//已领取

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("redPacketId", data);
                    bundle.putInt("type", 0);
                    startActivity(RedPackageDetailsActivity.class, bundle);
                } else {//退回
                    showToast(getString(R.string.red_package_already_overtime));
                }
            }
        });
    }

    /**
     * 打开红包
     *
     * @param uId
     */
    public void openRedPacket(final String uId) {

        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        mPgService.openRedPacket(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
                //new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(String data) {
                doRainRed();
                if (null != redDialog) redDialog.dismiss();
                initRedKLOpenFns(uId);
                mPgService.getRedPacketHistory(uId, ToolsUtils.getMyUserId()).
                        subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
                            @Override
                            protected void onResultError(ApiException ex) {
                                showToast(ex.getDisplayMessage());

                            }

                            @Override
                            public void onNext(RedPacketHistoryEntivity data) {

                                if (data != null) {
                                    doCancelRain();
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("redPacketId", data);
                                    bundle.putInt("type", 0);
                                    startActivity(RedPackageDetailsActivity.class, bundle);
                                }
                            }
                        });
                //  handler.sendEmptyMessageDelayed(99, 3000);
            }
        });
    }

    private void clearMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //清空当前聊天对象的未读信息
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and uniqueness=?", new String[]{fromid, destid + "", "_"});
                if (messageEntivities.size() > 0) {
                    MessageEntivity messageEntivity = messageEntivities.get(0);
                    messageEntivity.setMessageNum(0);
                    MessageEntivity.save(messageEntivity);
                }
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
            }
        }).start();

    }


    private static int tarPosition = 0;

    @Override
    protected void loadRecords() {

        pulltoLoadmore();
    }

    private void pulltoLoadmore() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadIMmessage();
            }
        }).start();
    }

    private void loadIMmessage() {
        isDown = true;
        if (pagelist != null) {
            pagelist.clear();
        }
        pagelist = ImMessage.find(ImMessage.class, "uniqueness=? ", new String[]{fromid + "_" + destid}, null, "send_time asc", page * number + "," + number);
        position = pagelist.size();
        Log.i("info", "size==加载数据==" + position);
        if (pagelist.size() != 0) {
            pagelist.addAll(tblist);
            int size = tblist.size();
            tblist.clear();
            tblist.addAll(pagelist);
            tbsizes = tblist.size();
            if (imageList != null) {
                imageList.clear();
            }
            if (imagePosition != null) {
                imagePosition.clear();
            }
            int key = 0;
            int position = 0;
            for (ImMessage cmb : pagelist) {
                if (cmb.getType() == ChatRecyclerAdapter.TO_USER_IMG) {//本机路径  这里考虑有转发
                    if (null != cmb.getFilePath() && !StringUtils.isEmpty(cmb.getFilePath())) {
                        //  Log.i("info","cmb.getfilepath=="+cmb.getFilePath());
                        imageList.add(new ImageInfoBean(cmb.getFilePath(), true));
                    } else {
                        ImageSendEntity sendEntity = JsonUtil.toObject(cmb.getContent(), ImageSendEntity.class);
                        if (sendEntity != null) {
                            imageList.add(new ImageInfoBean(sendEntity.getImagePath(), sendEntity.isCanForward()));
                        }
                        //  Log.i("info","cmb.getfileurl=="+cmb.getFileUrl());
                    }
                    imagePosition.put(key, position);
                    position++;
                } else if (cmb.getType() == ChatRecyclerAdapter.FROM_USER_IMG) {
                    imageList.add(new ImageInfoBean(cmb.getFileUrl(), IMMessageUtil.canImageForward(cmb)));
                    imagePosition.put(key, position);
                    position++;
                }
                key++;
            }
            tbAdapter.setImageList(imageList);
            tbAdapter.setImagePosition(imagePosition);
            if (wcLinearLayoutManger != null) {
                visibPosition = wcLinearLayoutManger.findFirstVisibleItemPosition();
                v = myList.getChildAt(visibPosition);
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //处理没有解决的已读消息
                    List<ReadedEntity> readedEntities = ReadedEntity.find(ReadedEntity.class, "uniqueness = ?", new String[]{fromid + "_" + destid});
                    if (readedEntities.size() > 0) {
                        for (int j = 0; j < readedEntities.size(); j++) {
                            for (int k = 0; k < tblist.size(); k++) {
                                if (readedEntities.get(j).getMsgid().equals(tblist.get(k).getMsgId())) {
                                    List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id =?", new String[]{tblist.get(k).getMsgId()});
                                    if (imMessages.size() > 0) {
                                        imMessages.get(0).setRead(true);
                                        imMessages.get(0).save();
                                    }
                                    tblist.get(k).setRead(true);
                                    readedEntities.get(j).delete();
                                }
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    tbAdapter.notifyDataSetChanged();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }).start();
            Log.i("info", "size==加载数据==");
            updateReadShow(false);
            if (null != tblist && tblist.size() > 0) {
                for (int j = tblist.size() - 1; j > 0; j--) {
                    /**  呵呵呵呵呵，这里对于ImMessage竟然没有正常的方法判断是发出还是接收！！！！生无所恋啊......... 精卫填海进行中... */
                    ImMessage imMessage = tblist.get(j);
                    if (null != imMessage) {
                        if (imMessage.getType() == ChatRecyclerAdapter.FROM_USER_MSG
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_IMG
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_VOICE
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_REDPACKET
                                || imMessage.getType() == ChatRecyclerAdapter.Lucky_Red_Envelope//接收到幸运红包
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_TRANSFER
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_TRANSFER_OTHER_GET
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_LOCATION
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_WITHDRAW_MSG
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_EMOJI
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_MSG_READ
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_FILE
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_VEDIO
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_PAYFOR
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_AA
                                || imMessage.getType() == ChatRecyclerAdapter.FROM_USER_READDELETE
                                ) {
                            saveFriendInfo(tblist.get(j));
                        }
                    }
                }
            }

            sendMessageHandler.sendEmptyMessage(PULL_TO_REFRESH_DOWN);
            if (page == 0) {
                pullList.refreshComplete();
                pullList.setPullGone();
                //myList.setRefreshComplete();
                myList.setPullRefreshEnabled(false);
            } else {
                pullList.setPull();
                myList.setPullRefreshEnabled(true);
                page--;
            }
        } else {
            if (page == 0) {
                pullList.refreshComplete();
                pullList.setPullGone();
                myList.setPullRefreshEnabled(false);
            }
        }
    }

    private void updateReadShow(final boolean isRefreshing) {
        /**
         * 这里做下处理
         * 情景：出现最后一条消息已读但前边几条未读（测试人员出现）
         */
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (null != tblist && tblist.size() > 0) {
                        boolean isread = false;
                        int start = -1;
                        int end = -1;
//                        for (int j = 0; j < tblist.size(); j++) {
                        try {
                            for (int j = tblist.size() - 1; j >= 0; j--) {
                                if (tblist.get(j).isRead() && -1 == end) {
                                    end = j;
                                }
                                if (isread) {
                                    if (!tblist.get(j).isRead()) {
                                        ImMessage imMessagel = tblist.get(j);
                                        imMessagel.setRead(true);
                                        tblist.set(j, imMessagel);
                                        List<ImMessage> imMessagelist = ImMessage.find(ImMessage.class, "msg_id=?", new String[]{tblist.get(i).getMsgId()});
                                        if (null != imMessagelist && imMessagelist.size() > 0) {
//                                    for (int j = 0; j < imMessagelist.size(); j++) {
                                            ImMessage imMessage = imMessagelist.get(0);
                                            imMessage.setRead(true);
                                            imMessage.save();
//                                    }
                                        }
                                        start = j;
                                    } else {
                                    }
                                } else {
                                    isread = tblist.get(j).isRead();
                                }
                            }
                            if (-1 != start) {
                                try {
                                    final int stt = start;
                                    int sum = 0;
                                    if (end > start) {

                                    } else {
                                        sum = tblist.size() - start;
                                    }
                                    final int msum = sum;
//                                if (isRefreshing)sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (null != tbAdapter && isRefreshing)
                                                tbAdapter.notifyItemRangeChanged(stt, msum);
                                        }
                                    });

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            mess_iv.setVisibility(View.GONE);
            sendBtn.setVisibility(View.VISIBLE);
        } else {
            mess_iv.setVisibility(View.VISIBLE);
            sendBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        // Log.i("info", "top ==" + top + ",bottom==" + bottom + ",oldtop==" + oldTop + ",oldbottom==" + oldBottom);
      /*  if (firstTag==-1){
            int i = oldBottom - bottom;
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,i);
            tbbv.setLayoutParams(lp);
        }*/
//        int recyclerHeight2 = wcLinearLayoutManger.getRecyclerHeight();
        if (screenHeight / 4 < (screenHeight - bottom) || bqmmKeyboard.getVisibility() == View.VISIBLE || tbbv.getVisibility() == View.VISIBLE) {
            // Log.i("info", "弹出键盘");
            if (tblist.size() > 0 && firstTag != -1) {
                myList.smoothScrollToPosition(tblist.size());
            }
        }
    }

    @Override
    public void onRefresh() {
        pulltoLoadmore();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onFinished(float seconds, String filePath) {
        sendVoice(seconds, filePath);
    }

    @Override
    public void onStart() {
        tbAdapter.stopPlayVoice();
        super.onStart();
    }

    static class SendMessageHandler extends Handler {
        private static final String TAG = "SendMessageHandler";
        WeakReference<ChatActivity> mActivity;//弱引用

        SendMessageHandler(ChatActivity activity) {
            mActivity = new WeakReference<ChatActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final ChatActivity theActivity = mActivity.get();
            if (theActivity != null) {
                final int itemCount = theActivity.tbAdapter.getItemCount();
                switch (msg.what) {
                    case REFRESH:
                        theActivity.tbAdapter.isPicRefresh = true;
                        theActivity.updateReadShow(false);
                        theActivity.tbAdapter.notifyDataSetChanged();
                        int position = itemCount < 0 ? 0 : itemCount;
                        theActivity.myList.smoothScrollToPosition(position);
                        break;
                    case REFRESH_FANYI:
                        theActivity.tbAdapter.isPicRefresh = true;
                        theActivity.tbAdapter.notifyDataSetChanged();
                        break;
                    case SEND_OK:
//                        theActivity.mEditTextContent.setText("");
                        theActivity.tbAdapter.isPicRefresh = true;
                        theActivity.updateReadShow(false);
                        theActivity.tbAdapter.setImageList(theActivity.imageList);
                        theActivity.tbAdapter.myNotifyDataSetChanged(theActivity.tblist);
                        if (theActivity.myList.getAlpha() == 0f) {
                            theActivity.myList.setAlpha(1f);
                        }
                        int postion = 0;
                        if (itemCount >= 0) {
                            postion = itemCount;
                        }
                        theActivity.myList.smoothScrollToPosition(postion);
                        break;
                    case UP_ERROR:
                        theActivity.showToast(theActivity.getResources().getString(R.string.nofile_fail));
                        theActivity.tblist.remove(theActivity.tblist.size() - 1);
                        try {
                            theActivity.tbAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case COMMIT_FINISH://文件上传完毕开始发送消息
                        String s = new Gson().toJson(theActivity.fileMsgEntivity);
                        theActivity.fileimMessage.setContent(s);
                        theActivity.socketSend(theActivity.fileimMessage, null, 0, 0);
                        break;
                    case RECERIVE_OK:
                        theActivity.tbAdapter.isPicRefresh = true;
                        try {
                            theActivity.tbAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        theActivity.myList.smoothScrollToPosition(itemCount);
                        if (firstTag == -1)
                            theActivity.myList.setAlpha(1f);
                        break;
                    case VEDIO_FINISH:

                       // theActivity.socketSend(theActivity.vedioMessage, null, 0, 0);
                        break;
                    case FILE_DOWNLOAD_OK:
                        theActivity.tbAdapter.isPicRefresh = true;
                        try {
                            theActivity.tbAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case PULL_TO_REFRESH_DOWN:
                        theActivity.pullList.refreshComplete();
                        try {
                            theActivity.tbAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        theActivity.myList.setRefreshComplete();
                        int alphatime = 0;
                        if (theActivity.tblist.size() <= 4) {
                            alphatime = 80;
                        } else if (theActivity.tblist.size() < 8) {
                            alphatime = 180;
                        } else {
                            alphatime = 400;
                        }
                        if (firstTag == -1)
                            theActivity.myList.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    theActivity.myList.setAlpha(1f);
                                }
                            }, alphatime);
                        if (theActivity.tbAdapter.getItemCount() <= theActivity.number) {
                            theActivity.myList.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    theActivity.myList.smoothScrollToPosition(theActivity.tbAdapter.getItemCount());
                                }
                            }, 50);
                        } else if (v != null && firstTag != -1) {
                            int top = v.getTop();
                            wcLinearLayoutManger.scrollToPositionWithOffset(15, top);
                        }
                        theActivity.isDown = false;
                        firstTag++;
                        break;
                    case SEND_CLEAN:
//                        theActivity.mEditTextContent.setText("");
                        break;
                    case Constant.ADAPTER_VOICE_FROM_DOWN_FINISH:
                        Log.i("info", "pathname==" + msg.obj);
                        break;
                    default:
                        break;
                }
            }
        }

    }

    /**
     * 发送文字  表情
     */
    @Override
    protected void sendMessage() {

        final String content = mEditTextContent.getText().toString();
        if (content == null || content.equals("")) {
            return;
        }
        mEditTextContent.setText("");
        setSocket();
        sendMessageHandler.sendEmptyMessage(SEND_CLEAN);
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_MSG, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, Constant.MESSAGE_TYPR_TEXT,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

        openklRed(content);

    }

    private void openklRed(String content) {
        if (null != mredPacketImMessage) {//点击自动发送口令
            try {
                RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(mredPacketImMessage.getContent());
                if (null != redPacketEntivity) {
                    if (content.equals(redPacketEntivity.getCommand())) {
                        openRedPacket("" + redPacketEntivity.getRedPacketId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (null != mRedMessages && mRedMessages.size() > 0) {
                try {
                    for (ImMessage imMessage : mRedMessages) {
                        if (null != imMessage) {
                            RedPacketEntivity redPacketEntivity = ToolsUtils.getRedPacket(imMessage.getContent());
                            if (null != redPacketEntivity) {
                                if (content.equals(redPacketEntivity.getCommand())) {
                                    openRedPacket("" + redPacketEntivity.getRedPacketId());
                                    return;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 撤回消息
     *
     * @param msgid
     */
    @Override
    protected void withdrawMsg(long msgid) {

        setSocket();

        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        WithdrawEntity withdrawEntity = new WithdrawEntity();
        withdrawEntity.setMsgid(sendmsgId);
        String s = new Gson().toJson(withdrawEntity);
        // Log.i("info", "s==" + s);
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_WITHDRAW_MSG, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, s, Constant.MESSAGE_TYPR_WITHDRAW,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        // List<ImMessage> imsgs = ImMessage.find(ImMessage.class, "uuid=?", msgid);

        ImMessage imsgs = ImMessage.findById(ImMessage.class, msgid);
        imsgs.delete();
        for (int e = 0; e < tblist.size(); e++) {
            ImMessage imMessage1 = tblist.get(e);
            if (imsgs.getMsgId().equals(imMessage1.getMsgId())) {
                tblist.remove(e);
                break;
            }
        }
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);
    }

    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub, final String address, final double lat, final double lut) {

        ImFriendEntivity friendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
        if (friendEntivity == null || "0".equals(friendEntivity.getIsFriend())) {
            //不是好友或者是单向好友
            tbub.setSendState(Constant.SENDERROR);
            tbub.save();
            IMMessageToJson.ImMessageToMessageEntivity(tbub, Constant.FROM_TYPE_SELF);

            if (friendEntivity != null) {
                //在插入一条提示加好友的消息
                ImMessage imMessage = new ImMessage();
                imMessage.setFromid(destid);
                imMessage.setFromname(friendEntivity.getName());
                imMessage.setFromType(Constant.FROM_TYPE_SYS);
                imMessage.setMsgId(UUID.randomUUID().toString());
                imMessage.setUniqueness(fromid + "_" + destid);
                imMessage.setDevType(Constant.DEV_TYPE);
                imMessage.setImageIconUrl("");
                imMessage.setSendTime(System.currentTimeMillis());
                imMessage.setDestid(Long.valueOf(fromid));
                imMessage.setType(ChatRecyclerAdapter.SHOW_NOT_FRIEND);
                imMessage.setSendState(Constant.COMPLETED);
                imMessage.save();
                tblist.add(imMessage);
            }
            sendMessageHandler.sendEmptyMessage(SEND_OK);
            return;
        }
        if (friendEntivity == null || "-1".equals(friendEntivity.getIsBlack())) {
            //不是好友或者是单向好友
            tbub.setSendState(Constant.SENDERROR);
            tbub.save();
            IMMessageToJson.ImMessageToMessageEntivity(tbub, Constant.FROM_TYPE_SELF);

            if (friendEntivity != null) {

                //在插入一条提示加好友的消息
                ImMessage imMessage = new ImMessage();
                imMessage.setFromid(destid);
                imMessage.setFromname(friendEntivity.getName());
                imMessage.setFromType(Constant.FROM_TYPE_SYS);
                imMessage.setMsgId(UUID.randomUUID().toString());
                imMessage.setUniqueness(fromid + "_" + destid);
                imMessage.setDevType(Constant.DEV_TYPE);
                imMessage.setImageIconUrl("");
                imMessage.setSendTime(System.currentTimeMillis());
                imMessage.setDestid(Long.valueOf(fromid));
                imMessage.setType(ChatRecyclerAdapter.Its_A_BLACKLIST);
                imMessage.setSendState(Constant.COMPLETED);
                imMessage.save();
                tblist.add(imMessage);
            }
            sendMessageHandler.sendEmptyMessage(SEND_OK);
            return;
        }

        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;

            @Override
            public void run() {
                if (tbub.getMessageType() != Constant.MESSAGE_TYPR_READ) {//已读
                    tbub.save();
                    ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    socketSend(imMessage);
                } else {
                    socketSend(tbub);
                }
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 2) {
                    boolean isSendToSocket = false;
                    if (retryCount == 1) {
                        imMessage.setSendState(Constant.SENDERROR);
                        if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                            imMessage.save();
                        }
                        tbub.setSendState(Constant.SENDERROR);
                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                        return;
                    }
                    try {//这里不能报异常
                        //imMessage.getType() == ChatRecyclerAdapter.TO_USER_IMG |
                        if (imMessage.getType() == ChatRecyclerAdapter.TO_USER_READDELETE | imMessage.getMessageType() == ChatRecyclerAdapter.TO_USER_IMG && !imMessage.getContent().contains("http"))//图片
                        {
                            if (imMessage.getFilePath() != null && imMessage.getFilePath().contains("storage") | imMessage.getFilePath().contains("sdcard")) {
                                Log.i(TAG, "socketSend: ===发图片TO_USER_IMG====001==");
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);//上传图片
                                Log.i(TAG, "socketSend: ===发图片TO_USER_IMG====002=response=" + response);
                                if ("0".equals(response) || "".equals(response)) {
                                    isSendToSocket = false;
                                } else {
                                    ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                    String url = imageEntity.getData().getInfo().get(0);
                                    if (imMessage.getMessageType() == ChatRecyclerAdapter.TO_USER_IMG) {
                                        ImageSendEntity sendEntity = JsonUtil.toObject(imMessage.getContent(), ImageSendEntity.class);
                                        if (sendEntity != null) {
                                            sendEntity.setImagePath(url);
                                            imMessage.setContent(JsonUtil.toJson(sendEntity));
                                        }
                                    } else {
                                        imMessage.setContent(url);
                                    }
                                    imMessage.setFileUrl(url);
                                    tbub.setContent(url);
                                    tbub.setFileUrl(url);
                                    isSendToSocket = true;
                                }
                            }
                            Log.i(TAG, "socketSend: ===发图片TO_USER_IMG====003==");
                        } else if (imMessage.getType() == ChatRecyclerAdapter.TO_USER_FILE) {//文件
                            Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====001==" + imMessage.getFilePath());
                            if (imMessage.getFilePath() != null) {
                                if (!imMessage.getFilePath().contains("http")) {
                                    // String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()));//上传文件
                                    String fileurl = HttpAssist.uploadFile(new File(imMessage.getFilePath()), imMessage.getMsgId(), true);//上传文件
                                    Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====002==fileurl=" + fileurl);
                                    if (null != fileurl && !fileurl.equals("0") && !fileurl.equals("")) {
                                        Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====003===");
                                        if (fileurl.contains("服务器异常")) {
                                            sendMessageHandler.sendEmptyMessage(UP_ERROR);
                                            Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====004===");
                                            continue;
                                        }
                                        try {
                                            Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====005===");
                                            ImageEntity imageEntity = new Gson().fromJson(fileurl, ImageEntity.class);
                                            imMessage.setFileUrl(imageEntity.getData().getInfo().get(0));
//                                            imMessage.setFilished(true);
//                                            sendMessageHandler.sendEmptyMessage(COMMIT_FINISH);
                                            isSendToSocket = true;
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====006===");
                                        }
                                    } else {
                                        Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====007===");
                                        showToast(getResources().getString(R.string.file_send_fail));//发送失败
                                        fileimMessage.setSendState(Constant.SENDERROR);
                                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                                        continue;
                                    }
                                } else {
                                    isSendToSocket = true;
                                }
                                Log.i(TAG, "socketSend: ===发文件TO_USER_FILE====008==isSendToSocket=" + isSendToSocket);
                            }
                        } else if (imMessage.getType() == ChatRecyclerAdapter.TO_USER_VOICE) {//声音
//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
                            if (!imMessage.getContent().contains("http")) {
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);
                                if ("0".equals(response) || "".equals(response)) {
                                    isSendToSocket = false;
                                } else {
                                    final ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);

//                                    runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
                                    String url = imageEntity.getData().getInfo().get(0);
                                    String contentStr = ToolsUtils.voiceEntivityToStr(url, imMessage.getUserVoiceTime());

                                    imMessage.setContent(contentStr);
                                    imMessage.setFileUrl(url);

                                    tbub.setContent(contentStr);
                                    tbub.setFileUrl(url);

                                    ChatActivity.this.seconds = imMessage.getUserVoiceTime();
                                    voiceFilePath = imgfilePath;
                                    isSendToSocket = true;
                                }
                            } else {
                                ChatActivity.this.seconds = imMessage.getUserVoiceTime();
                                voiceFilePath = imgfilePath;
                                isSendToSocket = true;
                            }

//                                        }
//                                    });
//
//                                }
//                            }).start();

//                            tblist.add(tbub);
//                            sendMessageHandler.sendEmptyMessage(SEND_OK);

                        } else if (imMessage.getType() == ChatRecyclerAdapter.TO_USER_LOCATION) {//位置
                            if (!imMessage.getContent().contains("http")) {
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);
                                if ("0".equals(response) || "".equals(response)) {
                                    isSendToSocket = false;
                                } else {
                                    ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                    String url = imageEntity.getData().getInfo().get(0);
                                    String s = ToolsUtils.locationEntivityToStr(url, address, lat, lut);
                                    if (null != response && response.contains("http")) {//上传成功 删除截图
                                        File imgfile = new File(imMessage.getFilePath());
                                        imgfile.delete();
                                    }
                                    imMessage.setContent(s);
                                    imMessage.setFileUrl(url);
                                    tbub.setContent(s);
                                    tbub.setFileUrl(url);
                                    isSendToSocket = true;
                                }
                            } else {
                                isSendToSocket = true;
                            }

                        } else if (imMessage.getType() == ChatRecyclerAdapter.TO_WITHDRAW_MSG) {//撤回消息
                            WithdrawEntity withdrawEntity = new WithdrawEntity();
                            withdrawEntity.setMsgid(sendmsgId);
                            String s = new Gson().toJson(withdrawEntity);
                            imMessage.setContent(s);//放入消息id
                            tbub.setContent(s);
                            isSendToSocket = true;
                        } else {
                            isSendToSocket = true;
                        }
                    } catch (Exception e) {
                        //没有网络时获取到的数据是错误的，不能使用gson转换
                        e.printStackTrace();
                    }
                    mSocket = App.socket;
                    retryCount++;
                    if (tblist.size() == 0) {//结束线程
                        imMessage.setSendState(Constant.SENDERROR);
                        if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                            imMessage.save();
                        }
                        return;
                    }

                    if (mSocket != null && isSendToSocket && mSocket.connected()) {
//                        imMessage.setSendState(Constant.COMPLETED);
//                        final ImMessage  mmimMessage1 = imMessage;
                        Log.i(TAG, "发送的图片路径：" + imMessage.getContent());
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                String message = args[0].toString();
                                ImMessage ss = IMMessageToJson.jsonToImMessage(message);
//                                Log.i("info", "发送的图片路径===" + imMessage.getContent() + "\n" + ss);
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                                    imMessage.save();
                                }
//                                mmimMessage1.setSendState(Constant.COMPLETED);
//                                tbub.setSendState(Constant.COMPLETED);
//                                if (mmimMessage1.getMessageType() != Constant.MESSAGE_TYPR_READ) {
//                                    mmimMessage1.save();
//                                }
                                Log.i(TAG, "call: ==========发送消息=============imMessage.getMessageType()=====" + imMessage.getMessageType());
                                if (null != tblist && tblist.size() > 0) {
                                    for (int j = 0; j < tblist.size(); j++) {
                                        if (("" + imMessage.getId()).equals("" + tblist.get(j).getId()) && imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                                            tblist.set(j, imMessage);
                                        }
                                    }
                                }

                                sendMessageHandler.sendEmptyMessage(SEND_OK);
                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    String filepath = "";//文件路径

    /**
     * 发送文件
     *
     * @param
     */
    @Override
    protected void sendFile(final String filepath) {
        setSocket();
        fileMsgEntivity = new FileMsgEntivity();
        InputStream is = null;
        String[] split = filepath.split("/");
        String filename = split[split.length - 1];//文件名
        fileMsgEntivity.setFileName(filename);
        try {
            is = new FileInputStream(new File(filepath));
            int available = is.available();//文件大小
            float i = (float) available / 1024 / 1024;
            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(i);
            fileMsgEntivity.setFileSize(format + "MB");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String content = new Gson().toJson(fileMsgEntivity);
        long currentTime = System.currentTimeMillis();
        fileimMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_FILE, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, Constant.MESSAGE_TYPR_FILE,
                currentTime, System.currentTimeMillis(), 0, filepath, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(fileimMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String fileurl = HttpAssist.uploadFile(new File(filepath), fileimMessage.getMsgId(), true);//上传文件
                if (null != fileurl && !fileurl.equals("0") && !fileurl.equals("")) {
                    if (fileurl.contains("服务器异常")) {
                        sendMessageHandler.sendEmptyMessage(UP_ERROR);
                        return;
                    }
                    try {
                        ImageEntity imageEntity = new Gson().fromJson(fileurl, ImageEntity.class);
                        fileMsgEntivity.setFileUrl(imageEntity.getData().getInfo().get(0));
                        fileMsgEntivity.setFilished(true);
                        sendMessageHandler.sendEmptyMessage(COMMIT_FINISH);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast(getResources().getString(R.string.file_send_fail));//发送失败
                    fileimMessage.setSendState(Constant.SENDERROR);
                    sendMessageHandler.sendEmptyMessage(SEND_OK);
                }
            }
        }).start();
    }

    //阅后即焚
    @Override
    protected void sendReadDelete(File imgfile) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_READDELETE, UUID.randomUUID().toString(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, imgfile.getPath(), Constant.MESSAGE_TYPR_READ_DELETE,
                currentTime, System.currentTimeMillis(), 0, imgfile.getPath(), fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(imMessage);
        // imageList.add(tblist.get(tblist.size() - 1).getFilePath());
        //imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        //ChatActivity.this.imgfilePath = imgfile.getPath();
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);
    }

//    //视屏通话
//    @Override
//    protected void sendCallVideo(String contenttype) {
//        setSocket();
//        long currentTime = System.currentTimeMillis();
//        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_CALLVIDEO, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
//                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, contenttype, Constant.MESSAGE_TYPR_CALL_VIDEO_FROM,
//                currentTime, System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, userEntivity.getHeadUrl());
//        tblist.add(imMessage);
//        sendMessageHandler.sendEmptyMessage(SEND_OK);
//        socketSend(imMessage, null, 0, 0);
//    }

    //语音通话
    @Override
    protected void sendCallVoice() {
        Intent intent = new Intent(this, CallFriendActivity.class);
        intent.putExtra("destid", destid);
        intent.putExtra("type", "voice");
        startActivity(intent);
    }

    //视频通话
    @Override
    protected void sendCallVideo() {
        Intent intent = new Intent(this, CallFriendActivity.class);
        intent.putExtra("destid", destid);
        intent.putExtra("type", "video");
        startActivity(intent);
    }


    /**
     * 发送图片
     */
    int i = 0;

    @Override
    protected void sendImage(ImageSendEntity imageSendEntity) {
        long currentTime = System.currentTimeMillis();
        Log.i(TAG, "sendImage: ===图片发送==filePath.getPath()=" + imageSendEntity.getImagePath());
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART,
                Constant.DEV_TYPE,
                0,
                ChatRecyclerAdapter.TO_USER_IMG,
                "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid),
                Constant.FROM_TYPE_MAM,
                destid,
                JsonUtil.toJson(imageSendEntity),
                Constant.MESSAGE_TYPR_IMAGE,
                currentTime,
                System.currentTimeMillis(),
                0,
                imageSendEntity.getImagePath(),
                fromid + "_" + destid,
                0,
                userEntivity.getHeadUrl());
        tblist.add(imMessage);
        imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFilePath(), imageSendEntity.isCanForward()));
        imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        ChatActivity.this.imgfilePath = imageSendEntity.getImagePath();
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);
    }

    /**
     * 接收图片
     */
    String imgfilePath = "";

    /**
     * 发送语音
     */
    @Override
    protected void sendVoice(final float seconds, final String filePath) {
        try {
            setSocket();
            long currentTime = System.currentTimeMillis();
            final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_VOICE, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, filePath, Constant.MESSAGE_TYPR_VOICE,
                    currentTime, System.currentTimeMillis(), 0, filePath, fromid + "_" + destid, seconds, userEntivity.getHeadUrl());
            tblist.add(imMessage);
            sendMessageHandler.sendEmptyMessage(SEND_OK);
            socketSend(imMessage, null, 0, 0);

            tbAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    /**
     * 发送位置
     *
     * @param imgFile
     * @param address
     * @param lat
     * @param lut
     */
    @Override
    protected void sendLocation(File imgFile, String address, double lat, double lut) {
        setSocket();

        long currentTime = System.currentTimeMillis();
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_LOCATION, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, imgFile.getPath(), Constant.MESSAGE_TYPR_LOCATION,
                currentTime, System.currentTimeMillis(), 0, imgFile.getPath(), fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(imMessage);
        //imageList.add(tblist.get(tblist.size() - 1).getFilePath());
        // imagePosition.put(tblist.size() - 1, imageList.size() - 1);
        //  ChatActivity.this.imgfilePath = imgFile.getPath();
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, address, lat, lut);
    }

    /**
     * 接收语音
     */
    float seconds = 0.0f;

    String voiceFilePath = "";

    //发送小视屏
    @Override
    protected void sendVedio(final VedioEntity vedioEntity) {
        setSocket();
        final String vedioPath = vedioEntity.getVedioPath();
        final String vedioBitmappath = vedioEntity.getVedioBitmappath();
        PathEntivity pathEntivity = new PathEntivity(vedioPath, vedioBitmappath);
        String s = new Gson().toJson(pathEntivity, PathEntivity.class);
        // InputStream is = null;
       /* try {
            is = new FileInputStream(new File(vedioPath));
            int available = is.available();//文件大小
            float i = (float) available / 1024 / 1024;
            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(i);
            vedioEntity.setVedioSize(format+"MB");
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        String content = new Gson().toJson(vedioEntity);
        long currentTime = System.currentTimeMillis();
        final ImMessage vedioMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_VEDIO, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, content, Constant.MESSAGE_TYPR_VEDIO,
                currentTime, System.currentTimeMillis(), 0, s, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(vedioMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        new Thread(new Runnable() {
            @Override
            public void run() {

                String vedioimgurl = HttpAssist.uploadFile(new File(vedioBitmappath), vedioMessage.getMsgId(), false);//上传缩略图
                // String destPath = vedioPath  + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) ;
                String destPath =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                String vediourl;
                if(ToolsUtils.getFileSize(new File(vedioPath))<ToolsUtils.MIN_STORAGE){
                    Log.d("huangrui","沒有壓縮:");
                    vediourl = HttpAssist.uploadFile(new File(vedioPath), vedioMessage.getMsgId(), false);//上传视屏
                 }else{
                    String filePath="";
                    Log.d("huangrui","输入路径:"+vedioPath);
                    try {
                        Log.d("huangrui","输出路径:"+destPath);
                        filePath = SiliCompressor.with(ChatActivity.this).compressVideo(vedioPath, destPath);
                        Log.d("huangrui","生成路径:"+filePath);
                    }catch (Exception e){

                    }


                     vediourl = HttpAssist.uploadFile(new File(filePath), vedioMessage.getMsgId(), false);//上传视屏
                    Log.d("huangrui","上传路径:"+vediourl);
                }


             //   String vedioimgurl = HttpAssist.uploadFile(new File(vedioBitmappath), vedioMessage.getMsgId(), false);//上传缩略图
              //  String vediourl = HttpAssist.uploadFile(new File(vedioPath), vedioMessage.getMsgId(), false);//上传视屏
                ImageEntity img1 = new Gson().fromJson(vedioimgurl, ImageEntity.class);
                ImageEntity img2 = new Gson().fromJson(vediourl, ImageEntity.class);
                vedioEntity.setVedioUrl(img2.getData().getInfo().get(0));
                vedioEntity.setGetVedioBitmapUrl(img1.getData().getInfo().get(0));
                //vedioEntity.setVedioPath(img1.getData().getInfo().get(0));
                 String vediocontent = new Gson().toJson(vedioEntity);
                vedioMessage.setContent(vediocontent);
                //sendMessageHandler.sendEmptyMessage(VEDIO_FINISH);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         socketSend(vedioMessage, null, 0, 0);
                    }
                });


            }
        }).start();
    }

    //接收录制的小视屏
    @Subscribe(threadMode = ThreadMode.MAIN) //
    public void onsendvedio(VedioEntity vedio) {
        if (vedio != null) {
            sendVedio(vedio);
        } else {
            showToast(getResources().getString(R.string.get_smallsp_fail));
        }
    }

    /**
     * 接收上传的速度
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void oncommitLenght(FileProEtivity lenth) {
        Log.i("info", "上传的速度==" + lenth.getCommitsize());
        tbAdapter.setProgressint(lenth.getCommitsize(), lenth.getLenth(), lenth.getMsgID());
    }

    private void saveFriendInfo(final ImMessage imMessage) {

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    /**
                     * 更新好友信息
                     */
                    ImFriendEntivity idFriendsInfo = ImFriendEntivity.findById(ImFriendEntivity.class, destid);
                    if ((!TextUtils.isEmpty(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(idFriendsInfo.getHeadUrl()))
                            || !imMessage.getFromname().equals(idFriendsInfo.getName())) {
                        idFriendsInfo.setHeadUrl(imMessage.getImageIconUrl());
                        idFriendsInfo.setName(imMessage.getFromname());
                        idFriendsInfo.save();//好友列表-个人信息
                    }

                    boolean isHaveNo = false;

                    if (null != tblist && tblist.size() > 0) {
//            for (int j = 0; j < tblist.size(); j++) {
                        int j = 0;
                        for (ImMessage imMessageM : tblist) {
                            if (imMessage.getFromid().equals(imMessageM.getFromid())) {
                                if ((!TextUtils.isEmpty(imMessage.getImageIconUrl()) && !imMessage.getImageIconUrl().equals(imMessageM.getImageIconUrl()))
                                        || !imMessage.getFromname().equals(imMessageM.getFromname())) {
                                    friendheadurl = imMessage.getImageIconUrl();

                                    imMessageM.setImageIconUrl(imMessage.getImageIconUrl());
                                    imMessageM.setFromname(imMessage.getFromname());
//                        imMessageM.save();
                                    tblist.set(j, imMessageM);

                                    isHaveNo = true;
                                }
                            }
                            j++;
                        }
                    }
                    if (isHaveNo) {
                        /**
                         * 思来想去，这个地方还是拿出来吧
                         * 强势一些，每次来都更新下，这样就可以只要有变化就全部更新
                         */
                        saveMessageAll(imMessage);

                        //聊天列表-个人信息
                        List<MessageEntivity> sysList3 = MessageEntivity.find(MessageEntivity.class, "uniqueness=? and fromid=? ", new String[]{ToolsUtils.getMyUserId() + "___", "" + imMessage.getFromid()});
                        if (null != sysList3 && sysList3.size() > 0) {
//                            for (int k = 0; k < sysList3.size(); k++) {
                            MessageEntivity messageEntivity = sysList3.get(0);
                            messageEntivity.setImgUrl(imMessage.getImageIconUrl());
                            messageEntivity.setNick(imMessage.getFromname());
                            messageEntivity.save();
//                            }
                        }
                        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                    }

                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void saveMessageAll(final ImMessage imMessage) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                List<ImMessage> imMessagelist = ImMessage.find(ImMessage.class,"uniqueness=? ", new String[]{fromid + "_" + destid});
                List<ImMessage> imMessagelist = ImMessage.find(ImMessage.class, "uniqueness=? ", new String[]{fromid + "_" + destid}, null, "send_time desc", 0 + "," + 50);// 0 + "," + 5
                if (null != imMessagelist && imMessagelist.size() > 0) {
                    for (int k = imMessagelist.size() - 1; k >= 0; k--) {
//                    for (int k = 0; k < imMessagelist.size(); k++) {
                        ImMessage imMessageN = imMessagelist.get(k);
                        imMessageN.setFromname(imMessage.getFromname());
                        imMessageN.setImageIconUrl(imMessage.getImageIconUrl());
                        imMessageN.save();
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        saveMessageAll2(imMessage);
                    }
                });
            }
        }).start();
    }

    private void saveMessageAll2(final ImMessage imMessage) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                List<ImMessage> imMessagelist = ImMessage.find(ImMessage.class,"uniqueness=? ", new String[]{fromid + "_" + destid});
                List<ImMessage> imMessagelist = ImMessage.find(ImMessage.class, "uniqueness=? ", new String[]{fromid + "_" + destid}, null, "send_time desc", "");// 0 + "," + 5
                if (null != imMessagelist && imMessagelist.size() > 0) {
                    for (int k = imMessagelist.size() - 1; k >= 0; k--) {
//                    for (int k = 0; k < imMessagelist.size(); k++) {
                        ImMessage imMessageN = imMessagelist.get(k);
                        imMessageN.setFromname(imMessage.getFromname());
                        imMessageN.setImageIconUrl(imMessage.getImageIconUrl());
                        imMessageN.save();
                    }
                }
            }
        }).start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImMessageEvent(final ImMessageData imMessage) {
        Log.i(TAG, "onImMessageEvent: ========1212=====2007===========");
//        Log.i(TAG, "onImMessageEvent: ========1212=====2007===========" + new Gson().toJson(imMessage));
        if (imMessage == null) return;
        tblist.add(imMessage.getImMessage());
//        sendMessageHandler.sendEmptyMessage(SEND_OK);
        sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
    }


    /**
     * 接收到消息
     *
     * @param imMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImMessageEvent(final ImMessage imMessage) {
//        Log.i(TAG, "onImMessageEvent: =========imMessage.getMessageType()========"+imMessage.getMessageType());
        if (imMessage.getFromType() != Constant.FROM_TYPE_MAM)//不是私聊不接受消息
        {
//            Log.i(TAG, "onImMessageEvent: =========imMessage.getMessageType()===001=====");
            return;
        }
        //Log.i("info","聊天界面接收到消息=="+imMessage.toString());
        if ((imMessage.getDestid() + "").equals(ToolsUtils.getMyUserId())) {
            tblist.add(imMessage);
            sendMessageHandler.sendEmptyMessage(SEND_OK);
//            Log.i(TAG, "onImMessageEvent: =========imMessage.getMessageType()===002=====");
            return;
        }
        if (imMessage.getDestid() != destid) {
//            Log.i(TAG, "onImMessageEvent: =========imMessage.getMessageType()===003=====");
            return;
        }
//        Log.i(TAG, "onImMessageEvent: =========imMessage.getMessageType()===004=====");
        switch (imMessage.getMessageType()) {
            case Constant.MESSAGE_TYPR_TEXT: {
                // Log.i("info","接收到文本消息"+imMessage.getContent());
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_MSG);
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_BQEMOJI: {
//                Log.i(TAG, "onImMessageEvent: ========1212================" + new Gson().toJson(imMessage));
                String content = imMessage.getContent();
                MsgEntity receirvemsg = new Gson().fromJson(content, MsgEntity.class);
                if (receirvemsg.getMsgCodes() != null && !"".equals(receirvemsg.getMsgCodes())) {
                    //大表情
                    imMessage.setType(ChatRecyclerAdapter.FROM_USER_EMOJI);
                } else {
                    //图文混排
                    imMessage.setType(ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT);
                }
//                Log.i(TAG, "onImMessageEvent: ======1212============================"+imMessage.getType());
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }

            case Constant.MESSAGE_TYPR_IMAGE: {
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_IMG);
                tblist.add(imMessage);
                imageList.add(new ImageInfoBean(tblist.get(tblist.size() - 1).getFileUrl(), IMMessageUtil.canImageForward(imMessage)));
                imagePosition.put(tblist.size() - 1, imageList.size() - 1);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_LOCATION: {
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_LOCATION);
                tblist.add(imMessage);
                String content = tblist.get(tblist.size() - 1).getContent();
                LocationEntivity locationentivity = new Gson().fromJson(content, LocationEntivity.class);
                imageList.add(new ImageInfoBean(locationentivity.getUrl(), true));
                imagePosition.put(tblist.size() - 1, imageList.size() - 1);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }

            case Constant.MESSAGE_TYPR_VOICE: {//收到语音
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_VOICE);
                Log.i("info", "收到语音前size=" + tblist.size());
                tblist.add(imMessage);
                Log.i("info", "收到语音后size=" + tblist.size());
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }

            case Constant.MESSAGE_TYPR_WITHDRAW: {//接收到消息撤回指令
                //根据id 去删除对应的记录、、TO_WITHDRAW_MSG
                String content = imMessage.getContent();

                // Log.i("info", "content=" + content);
                WithdrawEntity wd = new Gson().fromJson(content, WithdrawEntity.class);
                for (int q = 0; q < tblist.size(); q++) {//先从列表查询对应的消息
                    ImMessage imMessage1 = tblist.get(q);
                    //  Log.i("info", "撤回的id==" + imMessage1.getMsgId() + "---" + wd.getMsgid());
                    if (imMessage1.getMsgId().equals(wd.getMsgid())) {
                        tblist.remove(q);
                        imMessage1.delete();//从数据库删除
                        break;
                    }
                }
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }
            case Constant.MESSAGE_TYPR_READ://消息已读
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String content = imMessage.getContent();
                        try {
                            JSONArray jsonArray = new JSONArray(content);
                            if (jsonArray.length() > 0) {
                                JSONObject jsobj = jsonArray.getJSONObject(0);
                                final String msgid = jsobj.getString("id");
                                int pos = -1;
                                for (int m = 0; m < tblist.size(); m++) {
                                    ImMessage imsg = tblist.get(m);
                                    if (imsg.getMsgId().equals(msgid)) {
                                        List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id = ?", new String[]{msgid});
                                        if (imMessages.size() > 0) {
                                            imMessages.get(0).setRead(true);
                                            imMessages.get(0).save();
                                        }
                                        imsg.setRead(true);
                                        tblist.set(m, imsg);
                                        pos = m;
                                    }
                                }
                                List<ImMessage> readimMessages = ImMessage.find(ImMessage.class, "msg_id = ? ", new String[]{imMessage.getMsgId()});
                                if (readimMessages.size() > 0) {
                                    readimMessages.get(0).delete();
                                }
//                                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                                final int fpos = pos;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            if (-1 != fpos)
                                                tbAdapter.notifyItemRangeChanged(fpos + 1, 1);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        updateReadShow(true);
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                break;
            case Constant.MESSAGE_TYPR_FILE://收到文件消息  这里接收到后直接下载  如果下载失败  再次点击下载  这里判断是否有已经存在的文件
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_FILE);
                String content1 = imMessage.getContent();
                final FileMsgEntivity fileMsgEntivity = new Gson().fromJson(content1, FileMsgEntivity.class);
                tblist.add(imMessage);
                if (fileMsgEntivity != null) {
                    final String fileUrl = fileMsgEntivity.getFileUrl();//获取到文件下载路径 根据文件去判断是否存在
                    boolean exsite = ToolsUtils.isExsite(fileUrl);
                    if (!exsite) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String s1 = HttpAssist.fileDown(fileUrl, 1314, imMessage.getMsgId());//保存的本地路径
                                fileMsgEntivity.setFilished(true);
                                fileMsgEntivity.setFileUrl(s1);
                                String s = new Gson().toJson(fileMsgEntivity);
                                imMessage.setFilePath(s1);
                                imMessage.setContent(s);
                                ImMessage msg = imMessage;
                                ImMessage byId = ImMessage.findById(ImMessage.class, imMessage.getId());
                                if (byId != null) {
                                    byId.delete();
                                }
                                msg.save();
                                sendMessageHandler.sendEmptyMessage(FILE_DOWNLOAD_OK);
                            }
                        }).start();
                    } else {
                        //Log.i("info","文件已存在不用再次下载");
                        fileMsgEntivity.setFilished(true);
                        String s = new Gson().toJson(fileMsgEntivity, FileMsgEntivity.class);
                        imMessage.setContent(s);
                    }

                }
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_REDPACKTE:
            case Constant.MESSAGE_TYPR_TRANSFRE:
            case Constant.MESSAGE_TYPR_GET_REDPACKET:
            case Constant.MESSAGE_TYPR_TRANSFRE_OK:
            case Constant.MESSAGE_TYPR_TRANSFRE_BACK:
            case Constant.MESSAGE_TYPR_REDPACKET_BACK:
            case Constant.MESSAGE_TYPR_VEDIO://小视屏
            case Constant.MESSAGE_TYPR_AAMONEY_GET:
            case Constant.MESSAGE_TYPR_READ_DELETE:
            case Constant.MESSAGE_TYPR_CALL_VIDEO_FROM:
            case Constant.MESSAGE_TYPR_CALL_VIDEO_AS:
            case Constant.MESSAGE_TYPE_INVATE_JOIN_GROUP:
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            case Constant.MESSAGE_TYPR_FRIEND_HEAD: {//
                imMessage.setType(ChatRecyclerAdapter.FROM_USER_FRIEND_MP);
                tblist.add(imMessage);
                sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                break;
            }

        }
        if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ
                && Constant.MESSAGE_TYPR_WITHDRAW != imMessage.getMessageType())
            saveFriendInfo(imMessage);

    }

    private void setChatBG() {
        try {
            List<BGchat> bGchatList = BGchat.find(BGchat.class, "creatid=? and sessionid=?", new String[]{ToolsUtils.getMyUserId(), "" + destid});

            if (null != bGchatList && bGchatList.size() > 0) {
                BGchat bGchat = bGchatList.get(0);
                if ("".equals(bGchat.getBgchat())) {//单聊，默认
                    setChatBGAll();
                } else {//单聊，自己的设置
//                    Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                    Bitmap bitmap = BitmapFactory.decodeFile(bGchat.getBgchat(), new BitmapFactory.Options());
                    viewBack.setBackground(new BitmapDrawable(bitmap));
                }
            } else {//单聊，未设置
                setChatBGAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setChatBGAll() {
        try {
            List<BGsetAll> bGchatList = BGsetAll.find(BGsetAll.class, "creatid=?", new String[]{ToolsUtils.getMyUserId()});

            if (null != bGchatList && bGchatList.size() > 0) {
                BGsetAll bGchat = bGchatList.get(0);
                if ("".equals(bGchat.getBgpath())) {//默认
                    viewBack.setBackgroundColor(getResources().getColor(R.color.background));
                } else {//自己的设置
//                    Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                    Bitmap bitmap = BitmapFactory.decodeFile(bGchat.getBgpath(), new BitmapFactory.Options());
                    viewBack.setBackground(new BitmapDrawable(bitmap));
                }
            } else {//未设置
                viewBack.setBackgroundColor(getResources().getColor(R.color.background));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void findView() {
        super.findView();
        relative = (RelativeLayout) findViewById(R.id.root_relate);
        pullList.setSlideView(new PullToRefreshView(this).getSlideView(PullToRefreshView.RECYCLERVIEW));
        // myList = (PullToRefreshRecyclerView) pullList.returnMylist();
        myList = (PullToRefreshRecyclerView) findViewById(R.id.pulltorefreshrecyclerview);
        myList.setPullRefreshEnabled(true);
        myList.setLoadingMoreEnabled(false);
        myList.setPullToRefreshListener(this);

        screenHeight = ContentUtils.getScreenHeight(this);
        //听筒与免提控制
        // audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //听筒和免提切换
        speakerBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                audioModeManger.setSpeakerPhoneOn(!isspeakerphone);
                if (!isspeakerphone) {
                    isspeakerphone = true;
                    speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_nomarl));
                } else {
                    isspeakerphone = false;
                    speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_phone));
                }
                // setSpeakerphoneOn(isspeakerphone);
            }
        });
        //发送视屏通话
      /*  observer.setOnonCreateSuccess(new RtcSdpObserver.OnonCreateSuccess() {

            @Override
            public void sendoffer(SessionDescription sessionDescription) {
                Log.i(TAG, "sendoffer: 发起视屏通话");
                try{
                    //设置本地dsp
                    App.pc.setLocalDescription(observer,sessionDescription);
                    //发送offer给对方
                    JSONObject payload = new JSONObject();
                    payload.put("type", sessionDescription.type.canonicalForm());
                    payload.put("sdp", sessionDescription.description);
                    String content=payload.toString();
                    sendCallVideo(content);
                }catch (Exception e){
                    System.out.println("error.."+e.toString());
                }
            }
        });*/
        //表情云
        /*RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        myList.setLayoutParams(lp);*/
    }

    //切换听筒方法
   /* private void setSpeakerphoneOn(boolean on) {
        if (on) {
            audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.ROUTE_SPEAKER);
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                    audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL ),
                    AudioManager.STREAM_VOICE_CALL);
            isspeakerphone = false;
            speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_phone));
        } else {
           // Log.i("info", "听筒切换");
            audioManager.setSpeakerphoneOn(false);//关闭扬声器
            // audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            //把声音设定成Earpiece（听筒）出来，设定为正在通话中
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_nomarl));
            isspeakerphone = true;
        }
        // 听筒模式下设置为false
        // 设置成听筒模式
        //audioManager.setMode( AudioManager.MODE_IN_COMMUNICATION);
        // 设置为通话状态
        //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }*/

    @Override
    protected void initViews(Bundle savedInstanceState) {
        if (audioModeManger == null) {
            audioModeManger = new AudioModeManager(this);
        }
        audioModeManger.register();
    }

    @OnClick({R.id.pre_v_back, R.id.right, R.id.linear_bottom_kl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back: {
                ActivityUtil.closeSoftKeyboard(this);
                // scrollToFinishActivity();
                this.finish();
                break;
            }
            case R.id.right: {//个人信息
                Bundle bundle = new Bundle();
                bundle.putLong("destid", destid);
                startActivityForResult(ChatMgrActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
                break;
            }
            case R.id.linear_bottom_kl: {//口令点击
                String commant = txt_kl_content.getText().toString();
                if (null != commant && !"".equals(commant)) {
                    mEditTextContent.setText(commant);
                }
                linear_bottom_kl.setVisibility(View.GONE);
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_RED_PACKET_SEND:
                tbbv.setVisibility(View.GONE);
                mess_iv.setImageResource(R.drawable.tb_more);
                if (resultCode == 10) {
                    String destid = data.getStringExtra("destid");
                    String money = data.getStringExtra("money");
                    String liuyan = data.getStringExtra("liuyan");
                    String command = data.getStringExtra("command");
                    int type = data.getIntExtra("type", 0);
                    String redPacketId = data.getStringExtra("redPacketId");

                    ImMessage imMessage = null;

                    if (3 == type) {
                        imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_REDPACKET, uuid, Long.parseLong(fromid), Constant.FROM_TYPE_MAM, Long.parseLong(destid),
                                "{\"redPacketId\":\"" + redPacketId + "\",\"msg\":\"" + command + "\",\"command\":\"" + command + "\",\"redPacketType\":\"3\"}", Constant.MESSAGE_TYPR_REDPACKTE,
                                System.currentTimeMillis(), System.currentTimeMillis(), 0, imgfilePath, fromid + "_" + destid, 0, userEntivity.getHeadUrl());//
                    } else {
                        imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_REDPACKET, uuid, Long.parseLong(fromid), Constant.FROM_TYPE_MAM, Long.parseLong(destid),
                                "{\"redPacketId\":\"" + redPacketId + "\",\"msg\":\"" + liuyan + "\"}", Constant.MESSAGE_TYPR_REDPACKTE,
                                System.currentTimeMillis(), System.currentTimeMillis(), 0, imgfilePath, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
                    }

                    tblist.add(imMessage);
                    imMessage.save();
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                }
                break;
            case RESULT_TRANSFER_SEND:
                tbbv.setVisibility(View.GONE);
                mess_iv.setImageResource(R.drawable.tb_more);
                if (resultCode == 10) {
                    TransfreCreateEntivity transfreCreate = (TransfreCreateEntivity) data.getSerializableExtra("transfreCreate");
                    ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_TRANSFER, uuid, Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid,
                            "{\"transId\":\"" + transfreCreate.getId() + "\",\"msg\":\"" + transfreCreate.getMsg() + "\",\"amount\":\"" + transfreCreate.getAmount() + "\"}", Constant.MESSAGE_TYPR_TRANSFRE,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, imgfilePath, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
                    tblist.add(imMessage);
                    imMessage.save();
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                }
                break;
            case RESULT_TRANSFER_GET:
                if (resultCode == 10) {
                    TransferViewEntivity transfreCreate = (TransferViewEntivity) data.getSerializableExtra("TransferViewEntivity");

                    ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_TRANSFER_OTHER_GET, uuid, Long.parseLong(null == fromid ? "0" : ("".equals(fromid) ? "0" : fromid)), Constant.FROM_TYPE_MAM, destid,
                            "{\"transId\":\"" + transfreCreate.getId() + "\",\"msg\":\"" + transfreCreate.getMsg() + "\",\"amount\":\"" + transfreCreate.getAmount() + "\"}", Constant.MESSAGE_TYPR_TRANSFRE_OK,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, imgfilePath, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
                    tblist.add(imMessage);
                    imMessage.save();
                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    sendMessageHandler.sendEmptyMessage(RECERIVE_OK);
                }
                break;
            case Constant.MESSAGE_MAIN_GO_GROUP_RESULT:
                if (resultCode == Constant.MESSAGE_MAIN_GO_GROUP_RESULT) {
                    setResult(Constant.MESSAGE_MAIN_GO_GROUP_RESULT);
                    scrollToFinishActivity();
                }
                break;
            case SMALL_VEDIO://
                if (resultCode == RESULT_OK)
                    try {
                        String filePath = data.getStringExtra("videoUrl");
                        Log.e("lzf_video", filePath);
                        if (filePath != null && !filePath.equals("")) {
                            if (filePath.startsWith("file://")) {
                                filePath = data.getStringExtra("videoUrl").substring(7, filePath.length());
                            }
                            int duration = 0;
                            Log.i("info", "视频保存在：" + filePath);
                            //String[] split = filePath.split("/");
                            MediaMetadataRetriever media = new MediaMetadataRetriever();
                            media.setDataSource(filePath);
                            Bitmap bitmap = media.getFrameAtTime();
                            filePath.substring(0, filePath.lastIndexOf("/"));
                            String imgname = System.currentTimeMillis() + ".jpg";
                              /*  String urlpath = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/easyimVideo/" + imgname;*/
                            String urlpath = Environment.getExternalStorageDirectory() + "/" + imgname;
                            try {
                                duration = Integer.parseInt(media.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            File f = new File(urlpath);
                               /* File f = new File(Environment
                                        .getDownloadCacheDirectory().getPath()+ "/easyimVideo/", imgname);*/
                            if (f.exists()) {
                                f.delete();
                            }
                            try {
                                FileOutputStream out = new FileOutputStream(f);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();
                                //Log.i(TAG, "已经保存");
                                VedioEntity vedioEntity = new VedioEntity();
                                vedioEntity.setVedioPath(filePath);
                                vedioEntity.setVedioSize(duration);
                                vedioEntity.setCanForward(true);
                                vedioEntity.setVedioBitmappath(urlpath);
                                sendVedio(vedioEntity);
                            } catch (FileNotFoundException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            } catch (IOException e) {
                                showToast(getResources().getString(R.string.sp_hetpath_fail));
                                e.printStackTrace();
                            }

                        }
                    } catch (Exception ex) {
                    }
                break;
            case RESULT_LOCATION:
                if (resultCode == 11) {
                    String city = data.getStringExtra("city");//城市
                    String pro = data.getStringExtra("pro");//省
                    String des = data.getStringExtra("des");//描述
                    String district = data.getStringExtra("dis");//区
                    String street = data.getStringExtra("ste");//街道
                    String streetNum = data.getStringExtra("stenum");//街道号
                    String pic = data.getStringExtra("pic");//图片
                    String poi = data.getStringExtra("poi");//详细
                    double lat = data.getDoubleExtra("lat", 0);//经度
                    double lut = data.getDoubleExtra("lut", 0);//纬度
                    Log.i("info", "地图截屏成功开始发送" + pic);
                    File file = new File(pic);
                    StringBuffer strb = new StringBuffer("");
                    if (!district.equals("")) {
                        strb.append(district);
                    }
                    if (!street.equals("")) {
                        strb.append(street);
                    }
                    if (!streetNum.equals("")) {
                        strb.append(streetNum);
                    }
                    if (!poi.equals("")) {
                        strb.append(poi);
                    }
                    String addr = strb.toString();
                    sendLocation(file, addr, lat, lut);
                }
                break;
            case REQUST_SENDTOFRIEND:
                if (resultCode == REQUST_SENDTOFRIEND) {
                    scrollToFinishActivity();
                }
                break;
            case RESULT_SEND_FILE:
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        String realFilePath = ToolsUtils.getRealFilePath(this, uri);
                        Log.i("info", "realfilepaht==" + realFilePath);
                        String end = realFilePath.substring(realFilePath.lastIndexOf(".") + 1, realFilePath.length()).toLowerCase();
                        /* 依扩展名的类型决定MimeType */
                        if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                                end.equals("jpeg") || end.equals("bmp")) {
                            Log.i("info", "进来了");
                            Bitmap bitmap = PictureUtil.getSmallBitmap(realFilePath);
                            bitmap = PictureUtil.reviewPicRotate(bitmap, realFilePath);
                            File mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, realFilePath);
                            if (mCurrentPhotoFile != null && mCurrentPhotoFile.exists()) {
                                int size = ImageCheckoutUtil.getImageSize(bitmap);
                                sendImage(new ImageSendEntity(mCurrentPhotoFile.getAbsolutePath(), true));
                            } else {
                                showToast(getResources().getString(R.string.this_file_nonentity));
                            }
                        } else {
                            sendFile(realFilePath);
                        }
                        //File file = new File(realFilePath);
                        //Log.i("info","拿到的文件=="+realFilePath);
                    } catch (Exception e) {
                        showToast(getResources().getString(R.string.file_select_fail));
                    }
                }
                break;
            case ChatBottomViews.FROM_COLACTION:
                if (resultCode == 112211) {
                    ImMessage imessage = (ImMessage) data.getSerializableExtra("imessage");
                    if (imessage != null) {
                        setSocket();
                        tblist.add(imessage);
                        Log.i("info", "发送的消息为==" + imessage.toString());
                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                        socketSend(imessage, null, 0, 0);
                    }
                }
                break;
            case ChatBottomViews.FROM_FRIENDMP:
                if (resultCode == 10) {
                    String name = data.getStringExtra("friendname");
                    String id = data.getStringExtra("friendid");
                    String head = data.getStringExtra("headurl");
                    String imId = data.getStringExtra("imId");
                    ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_FRIEND_MP, UUID.randomUUID().toString(), Long.parseLong(null == fromid ? "0" : ("".equals(fromid) ? "0" : fromid)), Constant.FROM_TYPE_MAM, destid,
                            "{\"contactId\":\"" + id + "\",\"headUrl\":\"" + head + "\",\"nickName\":\"" + name + "\",\"IM\":\"" + imId + "\"}", Constant.MESSAGE_TYPR_FRIEND_HEAD,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, userEntivity.getHeadUrl());

                    if (imMessage != null) {
                        setSocket();
                        tblist.add(imMessage);
                        Log.i("info", "发送的消息为==" + imMessage.toString());
                        sendMessageHandler.sendEmptyMessage(SEND_OK);
                        socketSend(imMessage, null, 0, 0);

                    }
                }
                break;


        }
    }

    public void doRainRed() {

        red0.setVisibility(View.VISIBLE);
        red1.setVisibility(View.VISIBLE);
        red2.setVisibility(View.VISIBLE);
        red3.setVisibility(View.VISIBLE);
        red4.setVisibility(View.VISIBLE);
        red5.setVisibility(View.VISIBLE);
        red6.setVisibility(View.VISIBLE);
        red7.setVisibility(View.VISIBLE);
        red8.setVisibility(View.VISIBLE);
        red9.setVisibility(View.VISIBLE);
        red10.setVisibility(View.VISIBLE);
        red11.setVisibility(View.VISIBLE);
        red12.setVisibility(View.VISIBLE);
        red13.setVisibility(View.VISIBLE);

        shuxingSet(red0, 5100, 120, 700);
        shuxingSet(red1, 2800, 110, 300);
        shuxingSet(red2, 3900, 80, 500);
        shuxingSet(red3, 2800, 50, 380);
        shuxingSet(red4, 4600, -70, 400);
        shuxingSet(red5, 3800, -120, 700);
        shuxingSet(red6, 5800, -70, 3300);
        handler.sendEmptyMessageDelayed(0x100, 1500);
    }

    public void doCancelRain() {
        handler.removeMessages(0x100);
        handler.removeMessages(0x110);
        red0.setVisibility(View.GONE);
        red1.setVisibility(View.GONE);
        red2.setVisibility(View.GONE);
        red3.setVisibility(View.GONE);
        red4.setVisibility(View.GONE);
        red5.setVisibility(View.GONE);
        red6.setVisibility(View.GONE);
        red7.setVisibility(View.GONE);
        red8.setVisibility(View.GONE);
        red9.setVisibility(View.GONE);
        red10.setVisibility(View.GONE);
        red11.setVisibility(View.GONE);
        red12.setVisibility(View.GONE);
        red13.setVisibility(View.GONE);
    }

    public void shuxingSet(View view, int time, float trX, float raZ) {
        set = new AnimatorSet();
        ObjectAnimator taX = ObjectAnimator.ofFloat(view, "translationX", 0, trX);
        ObjectAnimator taY = ObjectAnimator.ofFloat(view, "translationY", 0, height + 150f);
        ObjectAnimator ra = ObjectAnimator.ofFloat(view, "rotation", 0, raZ);
        set.setDuration(time);
        set.play(taY).with(taX).with(ra);
        set.start();
    }

    /**
     * 翻译
     */
    //	appid+q+salt+密钥 的MD5值
    private String getMd5Text(String q) {
        String dengStr = PGApi.BDFY_APP_ID + q + ToolsUtils.getMyUserId() + PGApi.BDFY_MY;
        return MD5.MD532(dengStr);
    }

    private void getFanYi(String str, final int type) {
        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        // Log.i(TAG, "getFanYi: getLanguage=" + Locale.getDefault().getCountry());
//        Log.i(TAG, "getFanYi: getMyUserId="+ToolsUtils.getMyUserId());
        String biao = Locale.getDefault().getLanguage();
        if (biao.equals("zh")) {
            biao = biao + Locale.getDefault().getCountry();
        }
        mPgService.getTextFanYi(str, "auto", ToolsUtils.getMyFanYiMap().get(biao), PGApi.BDFY_APP_ID, ToolsUtils.getMyUserId(), getMd5Text(str)).subscribe(new AbsAPICallback<FanYiBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getString(R.string.commit_translante_defeat));
            }

            @Override
            public void onNext(FanYiBean data) {
                // Log.i(TAG, "onNext: fanyi=" + data);
                ImMessage imm = tblist.get(type);
                imm.setContent_fy(new Gson().toJson(data));
                imm.setIsShowFY("1");
                tblist.set(type, imm);
                sendMessageHandler.sendEmptyMessage(REFRESH_FANYI);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //好友解除了退出当前的聊天界面
    public void onFinish(String event) {
        if (event.equals(Constant.BYB_FRIEND)) {
            Toast.makeText(this, R.string.yout_friendship_already_finish, Toast.LENGTH_SHORT).show();
            finish();
        }
    }


    /**
     * @param //最外层布局
     * @param //要滚动的布局,就是说在键盘弹出的时候,你需要试图滚动上去的View,在键盘隐藏的时候,他又会滚动到原来的位置的布局
     *//*
    private void controlKeyboardLayout(final View root, final View needToScrollView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            private Rect r = new Rect();
            @Override
            public void onGlobalLayout() {

                //获取当前界面可视部分
                ChatActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = ChatActivity.this.getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                Log.i("info", "screeenHeight==" + screenHeight);
                int heightDifference = screenHeight - r.bottom;
                Log.i("info", "heightDifference==" + heightDifference);
                int recyclerHeight = 0;
                //int tagrheight = 0 ;
                if (wcLinearLayoutManger != null) {
                    recyclerHeight = wcLinearLayoutManger.getRecyclerHeight();
                    //根据字数判断高度
                    Log.i("info", "size===" + tblist.size());
                    Log.i("info", "recyclerHeight1==" + recyclerHeight);
                    if (tblist.size() > 0) {
                        int textlength = tblist.get((tblist.size() - 1)).getContent().length();
                        Log.i("info", "lenght==" + textlength);
                        if (textlength >= 36) {
                            recyclerHeight = recyclerHeight + ((textlength / 18-1) *60);
                        }
                    }
                    Log.i("info", "recyclerHeight2==" + recyclerHeight);
                    Log.i("info", "wcLinearLayoutManger.getHeight()" + wcLinearLayoutManger.getHeight());
                }
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) myList.getLayoutParams();
                int lpheight = layoutParams.height;
                Log.i("info", "lpheight==" + lpheight);
                if (heightDifference == bottomStatusHeight) {
                    if (emoji_group.getVisibility() == View.VISIBLE) {
                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight() - ScreenUtil.dip2px(ChatActivity.this, 210);
                        Log.i("info", "contentHeight1==" + contentHeight);
                        if (recyclerHeight < contentHeight) {
                            needToScrollView.scrollTo(0, 0);
                        } else {
                            if (recyclerHeight - contentHeight < ScreenUtil.dip2px(ChatActivity.this, 100)) {
                                float h = ScreenUtil.dip2px(ChatActivity.this, ScreenUtil.dip2px(ChatActivity.this, 30));
                                Log.i("info", "h30==" + h);
                                needToScrollView.scrollTo(0, (int) h);
                            } else {
                                float h = ScreenUtil.dip2px(ChatActivity.this, 225);
                                Log.i("info", "h225==" + h);
                                needToScrollView.scrollTo(0, (int) h);
                            }
                        }
                    } else if (tbbv.getVisibility() == View.VISIBLE) {
                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight() - ScreenUtil.dip2px(ChatActivity.this, 150);
                        Log.i("info", "contentHeight2==" + contentHeight);
                        if (recyclerHeight < contentHeight) {
                            needToScrollView.scrollTo(0, 0);
                        } else {
                            float h = ScreenUtil.dip2px(ChatActivity.this, 150) + 50;
                            Log.i("info", "h50==" + h);
                            needToScrollView.scrollTo(0, (int) h);
                        }
                    } else {
                        needToScrollView.scrollTo(0, 0);
                    }
                } else {
                    if (heightDifference < recyclerHeight) {
                            myList.scrollToPosition(tblist.size()-1);//
                        int contentHeight = wcLinearLayoutManger == null ? 0 : wcLinearLayoutManger.getHeight();
                        Log.i("info", "contentHeight3==" + contentHeight);
                        if (recyclerHeight < contentHeight) {
                           // listSlideHeight = heightDifference - (contentHeight - recyclerHeight);
                            listSlideHeight = recyclerHeight-heightDifference ;
                            Log.i("info", "listheight1==" + listSlideHeight);
                            needToScrollView.scrollTo(0, listSlideHeight + 105);
                        } else {
                            listSlideHeight = heightDifference;
                            Log.i("info", "listheight2==" + listSlideHeight);
                            needToScrollView.scrollTo(0, listSlideHeight + 50);
                        }
                    } else {
                        listSlideHeight = 0;
                    }
                }
                Log.i("info","hei=="+wcLinearLayoutManger.getRcHeight());
            }
        });
    }*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPaystring(PayString code)//在ui线程执行
    {
        if (code != null) {
            String msgid = code.getMsgid();
            List<ImMessage> imMessages = ImMessage.find(ImMessage.class, "msg_id=?", new String[]{msgid});
            if (imMessages.size() > 0) {
                imMessages.get(0).setPayed(true);
                imMessages.get(0).save();
            }
            for (int i = 0; i < tblist.size(); i++) {
                if (tblist.get(i).getMsgId().equals(msgid)) {
                    tblist.get(i).setPayed(true);
                    tbAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClearEvent(String code)//在ui线程执行
    {
        if (code.equals(Constant.BLACK_CLEAR_CHAT_MESSAGE_REFRESH)) {
            try {
                pagelist.clear();
                tblist.clear();
                myList.setPullRefreshEnabled(false);
                tbAdapter.notifyDataSetChanged();
                showToast(getString(R.string.chat_history_clean_success));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (code.equals(Constant.CLOSE_CHAT_ACTIVITY)) {
            finish();
        } else if (code.equals(Constant.APP_DESTID_CHAT_ACTIVITY)) {
            App.destid = destid;
        } else if (code.equals(Constant.STAR_PLAY_VOICE)) {
            speakerBt.setVisibility(View.VISIBLE);
            speakerBt.setEnabled(true);
        } else if (code.equals(Constant.STOP_PLAY_VOICE)) {
            Log.i("wgdinfo", "onClearEvent: ------STOP_PLAY_VOICE----000-----------");
            speakerBt.setVisibility(View.GONE);
            speakerBt.setEnabled(false);
            if (playingItemvoice != -1) {
                Log.i("wgdinfo", "onClearEvent: ------STOP_PLAY_VOICE----111-----------");
                setstopvoice(playingItemvoice);
            }

        }
    }

    /**
     * @param view
     * @param withdraw 是否可以撤回
     */
    public void initMenu(View view, final boolean withdraw, final int type, boolean canForward) {
        popupMenu = new PopupMenu(this, view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_chat, menu);
        MenuItem item = menu.getItem(2);
        if (withdraw) {
            item.setTitle(getResources().getString(R.string.withdraws)); //这里对消息进行判断  是否可以撤回
        } else {
            item.setTitle(getResources().getString(R.string.delete));
        }
        switch (type) {
            case ChatRecyclerAdapter.TO_USER_VOICE:
            case ChatRecyclerAdapter.FROM_USER_VOICE:
                if (isspeakerphone) { //听筒
                    menu.getItem(0).setTitle(getResources().getString(R.string.goto_mt));
                } else {
                    menu.getItem(0).setTitle(getResources().getString(R.string.goto_tt));
                }
                break;
            case ChatRecyclerAdapter.TO_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_EMOJI:
            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
//                menu.add("复制");
                menu.getItem(3).setTitle(getResources().getString(R.string.copy));

                break;
          /*  case ChatRecyclerAdapter.FROM_USER_FILE:
                if (withdraw){
                    menu.getItem(0).setTitle("转发给其他好友");
                }else {
                    menu.getItem(0).setTitle("");
                }
                break;*/
        }
        switch (type) {
            case ChatRecyclerAdapter.TO_USER_LOCATION:
            case ChatRecyclerAdapter.FROM_USER_LOCATION:
            case ChatRecyclerAdapter.TO_USER_IMG:
            case ChatRecyclerAdapter.FROM_USER_IMG:
            case ChatRecyclerAdapter.TO_USER_MSG:
            case ChatRecyclerAdapter.FROM_USER_MSG:
            case ChatRecyclerAdapter.FROM_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI:
            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
            case ChatRecyclerAdapter.FROM_USER_FILE:
            case ChatRecyclerAdapter.FROM_USER_VEDIO:
            case ChatRecyclerAdapter.TO_USER_FILE:
            case ChatRecyclerAdapter.TO_USER_VEDIO:
                menu.getItem(0).setVisible(canForward);
                menu.getItem(1).setVisible(canForward);
                break;
        }
        popupMenu.show();
        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.add_contacts://发给朋友 切换听筒
                        switch (type) {
                            case ChatRecyclerAdapter.TO_USER_VOICE:
                            case ChatRecyclerAdapter.FROM_USER_VOICE:
                                if (isspeakerphone) { //听筒
                                    audioModeManger.setSpeakerPhoneOn(true);
                                    //  audioManager.setSpeakerphoneOn(true);
                                    isspeakerphone = false;
                                    showToast(getResources().getString(R.string.goto_mt));
                                } else {
                                    //  audioManager.setSpeakerphoneOn(false);//关闭扬声器
                                    // audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
                                    //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                                    //把声音设定成Earpiece（听筒）出来，设定为正在通话中
                                    //audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                                    audioModeManger.setSpeakerPhoneOn(false);
                                    speakerBt.setImageDrawable(getResources().getDrawable(R.drawable.speaker_nomarl));
                                    isspeakerphone = true;
                                    showToast(getResources().getString(R.string.goto_tt));
                                }
                                break;
                            case ChatRecyclerAdapter.TO_USER_LOCATION:
                            case ChatRecyclerAdapter.FROM_USER_LOCATION:
                            case ChatRecyclerAdapter.TO_USER_IMG:
                            case ChatRecyclerAdapter.FROM_USER_IMG:
                            case ChatRecyclerAdapter.TO_USER_MSG:
                            case ChatRecyclerAdapter.FROM_USER_MSG:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI:
                            case ChatRecyclerAdapter.TO_USER_EMOJI:
                            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.FROM_USER_FILE:
                            case ChatRecyclerAdapter.FROM_USER_VEDIO:
                            case ChatRecyclerAdapter.TO_USER_FILE:
                            case ChatRecyclerAdapter.TO_USER_VEDIO:
                                Intent intent = new Intent(ChatActivity.this, SelecteLocalFriendActivity.class);
                                intent.putExtra("tag", 11);
                                intent.putExtra("msg", choseimMessage);
                                startActivityForResult(intent, REQUST_SENDTOFRIEND);
                                break;
                        }
                        break;
                    case R.id.create_group: //收藏
                        String colactiontype = "";
                        if (choseimMessage != null) {
                            Integer messageType = choseimMessage.getMessageType();
                            if (messageType == Constant.MESSAGE_TYPR_TEXT | messageType == Constant.MESSAGE_TYPR_BQEMOJI) {
                                colactiontype = "1";
                            } else if (messageType == Constant.MESSAGE_TYPR_IMAGE) {
                                colactiontype = "2";
                            } else if (messageType == Constant.MESSAGE_TYPR_VOICE) {
                                colactiontype = "3";
                            } else if (messageType == Constant.MESSAGE_TYPR_VEDIO) {
                                colactiontype = "4";
                            } else {
                                ToolsUtils.showToast(ChatActivity.this, getResources().getString(R.string.message_nocoll));
                            }
                            if (!"".equals(colactiontype))
                                Log.i("info", "content===" + choseimMessage.getContent());
                            mPgService.addcolaction(colactiontype, choseimMessage.getImageIconUrl(), choseimMessage.getContent(), choseimMessage.getFromname(), ToolsUtils.getMyUserId(), choseimMessage.getFromid() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
                                @Override
                                protected void onResultError(ApiException ex) {
                                    if (ex != null) {
                                        String displayMessage = ex.getDisplayMessage();
                                        try {
                                            JSONObject object = new JSONObject(displayMessage);
                                            JSONObject data = object.getJSONObject("data");
                                            String info = data.getString("info");
                                            ToolsUtils.showToast(ChatActivity.this, info);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                                @Override
                                public void onNext(ValidateEntivity validateEntivity) {
                                    if (validateEntivity != null) {
                                        ToolsUtils.showToast(ChatActivity.this, validateEntivity.getInfo());
                                    }
                                }
                            });
                            // showToast("敬请期待收藏功能！");
                        }
                        break;

                    case R.id.search_group: //删除  撤回
                        if (withdraw) {
                            withdrawMsg(sendMsgId);
                            // item.setTitle("撤回"); //这里对消息进行判断  是否可以撤回
                        } else {
                            ImMessage msgbyId = ImMessage.findById(ImMessage.class, sendMsgId);
                            if (msgbyId != null) {
                                msgbyId.delete();//从本地数据库删除
                            }
                            for (int o = 0; o < tblist.size(); o++) {
                                ImMessage imMessage = tblist.get(o);
                                if (imMessage.getMsgId().equals(msgbyId.getMsgId())) {
                                    tblist.remove(o);
                                    break;
                                }
                            }
                            tbAdapter.notifyDataSetChanged();
                            // item.setTitle("删除");
                        }
                        break;

                    case R.id.scan: //更多
                        Log.i(TAG, "onMenuItemClick: ===============进入剪切判断===001=========");
                        switch (type) {
                            case ChatRecyclerAdapter.TO_USER_EMOJI:
                            case ChatRecyclerAdapter.TO_USER_EMOJI_TEXT:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI:
                            case ChatRecyclerAdapter.FROM_USER_EMOJI_TEXT:
                                if (null != choseimMessage) {
                                    String content = "";
                                    try {
                                        MsgEntity msgentity = new Gson().fromJson(choseimMessage.getContent(), MsgEntity.class);
                                        if (null != msgentity) {
                                            content = msgentity.getMsgString();
                                        }
                                        //获取剪贴板管理器：
                                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 创建普通字符型ClipData
                                        ClipData mClipData = ClipData.newPlainText("Label", content);
                                        // 将ClipData内容放到系统剪贴板里。
                                        cm.setPrimaryClip(mClipData);
                                        if (null != content && !"".equals(content))
                                            showToast(getResources().getString(R.string.copy_to_jqb));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                break;
                            default:
                                showToast(getResources().getString(R.string.more_faction_l));
                                break;
                        }

                        // startActivityForResult(CommonScanActivity.class, richScanCode);
                        break;


                    default:
                        break;
                }
                return false;
            }
        });

    }

    private void initBQmm() {
        bqmm = BQMM.getInstance();
        //注册UI中的EditView、Keyboard和SendButton
        bqmm.setEditView(mEditTextContent);
        bqmm.setKeyboard(bqmmKeyboard);
        bqmm.setSendButton(sendBtn);
        bqmm.load();
       /* sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("info","点击了");
            }
        });*/
        // Log.i("info","sendbt=="+bqmm.getSendButton());
        bqmm.setBqmmSendMsgListener(new IBqmmSendMessageListener() {
            @Override
            public void onSendFace(Emoji face) {
                JSONArray msgCodes = BQMMMessageHelper.getFaceMessageData(face);
                MsgEntity msgEntity = new MsgEntity();
                msgEntity.setMsgCodes(msgCodes.toString());
                msgEntity.setMsgString(BQMMMessageHelper.getFaceMessageString(face));
                msgEntity.setMsgType(BQMMMessageText.FACETYPE);
                String msg = new Gson().toJson(msgEntity);
                sendMsg(msg, ChatRecyclerAdapter.TO_USER_EMOJI);
            }

            @Override
            public void onSendMixedMessage(List<Object> emojis, boolean isMixedMessage) {
                String msgString = BQMMMessageHelper.getMixedMessageString(emojis);
                MsgEntity msgEntity = new MsgEntity();
                if (isMixedMessage) {
                    JSONArray msgCodes = BQMMMessageHelper.getMixedMessageData(emojis);
                } else {
                    msgEntity.setMsgString(msgString);
                    String msg = new Gson().toJson(msgEntity);
                    sendMsg(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT);
                }
            }
        });
    }

    protected void sendMsgTime(String msgjson, int typecode, int friend_id) {
        if (msgjson == null || msgjson.equals("")) {
            return;
        }
        setSocket();
        sendMessageHandler.sendEmptyMessage(SEND_CLEAN);
        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + friend_id + "-" + fromid + "-" + System.currentTimeMillis();
        Log.i("wgdinfo", "sendMsg: ----头像头像头像--------userEntivity.getHeadUrl()=" + userEntivity.getHeadUrl());
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, typecode, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, msgjson, Constant.MESSAGE_TYPR_BQEMOJI,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + friend_id, 0, userEntivity.getHeadUrl());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

        try {
            MsgEntity msgEntity = new Gson().fromJson(msgjson, MsgEntity.class);
            openklRed(msgEntity.getMsgString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void sendMsg(String msgjson, int typecode) {
        if (msgjson == null || msgjson.equals("")) {
            return;
        }
        setSocket();
        sendMessageHandler.sendEmptyMessage(SEND_CLEAN);
        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        Log.i("wgdinfo", "sendMsg: ----头像头像头像--------userEntivity.getHeadUrl()=" + userEntivity.getHeadUrl());
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, typecode, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, msgjson, Constant.MESSAGE_TYPR_BQEMOJI,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);
        socketSend(imMessage, null, 0, 0);

        try {
            MsgEntity msgEntity = new Gson().fromJson(msgjson, MsgEntity.class);
            openklRed(msgEntity.getMsgString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null || !mSocket.connected()) {//mSocket 为空  这个基本不会出现 、或者链接断开了
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
            // App.initSocket(App.imIpAfterReady, App.tokenAfterReady);
        }
    }

    //重写此方法解决AudioManager 导致的内存泄漏
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }

    private void startPropertyAnim() {
        // 将直接把TextView这个view对象的透明度渐变。
        // 注意第二个参数："alpha"，指明了是透明度渐变属性动画
        // 透明度变化从1—>0.1—>1—>0.5—>1，TextView对象经历4次透明度渐变
        ObjectAnimator anim = ObjectAnimator.ofFloat(myList, "alpha", 0f, 1f);
        anim.setDuration(1000);// 动画持续时间
        // 这里是一个回调监听，获取属性动画在执行期间的具体值
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                Log.i("info", "透明度==" + value);
            }
        });

        anim.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (tbbv.getVisibility() == View.VISIBLE) {
                tbbv.setVisibility(View.GONE);
                mess_iv.setImageResource(R.drawable.tb_more);
                return true;
            }
        }
        super.onKeyDown(keyCode, event);
        return false;
    }

    /**
     * 添加好友
     *
     * @param string
     */
    private void requestFriend(String string) {
//        Log.i(TAG, "添加好友requestFriend: destId = " + mFriendEntivity.getId() + "--myId = " + ToolsUtils.getMyUserId());

        PGService.getInstance().getNetApi().authenticationRequestNotice(ToolsUtils.getMyUserId(), "" + destid, "2",string)
                .compose(RxJavaUtil.<ValidateEntivity>applySchedules())
                .compose(this.<ValidateEntivity>applyProgress(null))
                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    public void onNext(ValidateEntivity addFriendEntity) {
                        /** 加好友使用，不会大量发送 */
                        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);//通知刷新界面
                        showToast(getResources().getString(R.string.friend_apply_already_commit));
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        try {
                            /*{"code":"2","data":"{\"info\":\"完成 \"}"}*/
                            AddFriendResultEntivity resultModel = new Gson().fromJson(ex.getDisplayMessage(), AddFriendResultEntivity.class);
                            if ("2".equals(resultModel.getCode())) {
                                getUserById(destid + "");
                            }
                        } catch (Exception e) {
                            showToast(getResources().getString(R.string.friend_apply_already_commitno));
                        }
                        Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                    }
                });
    }

    /**
     * 根据好id查询详情（此处用于添加好友），查询完成后保存数据库
     *
     * @param destid
     */
    private synchronized void getUserById(String destid) {

        String fromid = ToolsUtils.getMyUserId();

        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivity) {

                UserEntivity userEntivity = ToolsUtils.getUser();
                //更新数据库
                mFriendEntivity.setCurrentid(userEntivity.getId());
                mFriendEntivity.setIsBlack("0");
                mFriendEntivity.save();
                mFriendEntivity.setId(mFriendEntivity.getId());
                mFriendEntivity.save();
                //刷新好友页面数据
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                showToast(getResources().getString(R.string.add_success));
            }

            @Override
            protected void onResultError(ApiException ex) {
//                showToast(ex.getDisplayMessage());
                //  Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }
}
